JAVA Objectives Question?

Ads
 

JAVA Objectives Question?

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

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);
        }
    }
}

Ads









Related Tutorials/Questions & Answers:
JAVA Objectives Question?
Java Objectives Question
Advertisements
Core Java Interview Questions Page 2, Core Java QuestionQ
java questions
java questions
java questions
java questions
Java Questions
Java Questions
java questions
java questions
java Questions
Java Interview Questions
Java Questions & Java FAQ
Interview Questions - What is Java?
Questions about Java's String pool
Java - Java Interview Questions
Java - Java Interview Questions
Java - Java Interview Questions
java - Java Interview Questions
Interview Questions - Where Java is used?
Java interview questions and answers
Interview Questions - How Java is Used?
Java interview questions
cms - Java Interview Questions
urgent - Java Interview Questions
Java - Servlet Interview Questions
Core Java Interview questions and answers
Interview Questions - What are important features of Java?
Collection of Large Number of Java Interview Questions!
Java Interview Questions with Answers

Ads