bob
JAVA Objectives Question?
1 Answer(s)      3 years and a month ago
Posted in : Java Beginners

Write an application using the FileInputStream that opens a file that contains the name of the user's favorite book and then displays it to the user. If the file does not exist, prompt the user for the book's title and then write it to the file by using a FileOutputStream. Save the file as DisplayBook.java

Advertisement
View Answers

July 3, 2012 at 3:33 PM


Here is a code that checks whether the given file exists or not. If file exists,then the code will display the data. Otherwise, it will allow the user to enter title's name and write it to the file. We have used FileInputStream and FileOutputStream for I/O operations.

import java.io.*;

class DisplayBook {
    public static void main(String[] args) 
    {
        int ch;
        try{
        File f=new File("c:/b.txt");
        if(f.exists()){
        StringBuffer buffer=new StringBuffer("");
        FileInputStream fis=new FileInputStream(f);
        while ((ch = fis.read()) != -1){
         buffer.append((char) ch);
        }
        System.out.println(buffer.toString());
        fis.close();
        }
        else{
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.print("Enter Title: ");
            String str=br.readLine();
            FileOutputStream fos=new FileOutputStream(f);
            byte buf[] = str.getBytes();
            for (int i=0; i < buf.length; i += 2) {
             fos.write(buf[i]);
            } 
            fos.close();
        }
       }
        catch(Exception e){
        System.out.println(e);
        }
    }
}