Question

Java Write an application using the FileInputStream that OPENS a file which contains the name of...

Java

Write an application using the FileInputStream that OPENS a file which 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 BookApplication.java.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

public class BookApplication {

   public static void main(String[] args) {
       // TODO Auto-generated method stub
       Scanner sc=new Scanner(System.in);
       try{
               File f = new File("book.txt");//to check if file exists or not
               if(!f.exists()){//if file doesn't exist create a new one and ask user for book name and write to it
                   f.createNewFile();
       OutputStream outputStream = new FileOutputStream("book.txt");
               System.out.println("Enter favorite book");
               String bookname=sc.nextLine();
               outputStream.write(bookname.getBytes());
               }else{//if file exists read book name from the file and display to user
           InputStream inputStream = new FileInputStream("book.txt");
           int ch;
           while((ch=inputStream.read())!=-1)
           System.out.print((char)ch);
               }
      
      
       } catch (IOException ex) {
       ex.printStackTrace();
       }

   }

}

Expected output:

when file doesn't exist the output will be

After writing data to file when file exists output will be

Add a comment
Know the answer?
Add Answer to:
Java Write an application using the FileInputStream that OPENS a file which contains the name of...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT