Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program that carries out the following tasks: Open a file with the name

ID: 3704201 • Letter: W

Question

Write a program that carries out the following tasks: Open a file with the name hello.txt; Store the message "Hello World!" in the file; Close the file; Open the same file again; Read the message into a string variable and print it. The program should be designed to handle a 'File not found' exception.

It has to follow the format below:

import java.io.*;

public class Hello_World {
public static void main(String [] args) throws FileNotFoundException {
PrintStream output = new PrintStream(new File("hello.text"));
output.println("Hello World!");
output.println();
}
}

Explanation / Answer

Let me know if you have any doubts.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;


public class Hello_World {

  
   public static void main(String[] args) {
       try{
   File file = new File("hello.txt");
   PrintWriter pw = new PrintWriter(file);
   pw.write("Hello World!");
   pw.flush();
   pw.close();
   Scanner scan = new Scanner(file);
   String msg = scan.nextLine();
   System.out.println(msg);
   scan.close();
       }
       catch(FileNotFoundException e){
           System.out.println("File does not exist");
       }
   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote