Computing

java code

Reading a text file – Java code

Details:

Name: readFile.java (Java version: 16.0.1)
Description: This code requests that the user input a file name. The file will be read as text, line by line, and each line will be printed on the monitor screen. The reading continues until the end of the file is reached. The file is then closed and the program stops. If the file cannot be found, an error message will appear, and the program will be terminated.
import java.util.Scanner; 
import java.io.File;
import java.io.FileNotFoundException;

class readFile {

   public static void main(String[] args) {
      Scanner obj = new Scanner(System.in); // Create a Scanner object
      System.out.println("Enter file name");      
      String filename = obj.nextLine(); // read user input for file name
      // Open and read the file's contents, line by line as text, and print it to screen. 
      // Print an error message if the file does not exist.
      try {
         File myObj = new File(filename);
         Scanner myReader = new Scanner(myObj);  
         while (myReader.hasNextLine()) {
            String data = myReader.nextLine();
            System.out.println(data);
         }
      myReader.close();
      } catch (FileNotFoundException e) {
         System.out.println("An error occurred.");
         e.printStackTrace();
      }    
   }

}