Java Tutorial-Java Read Files

Read a File


We use the Scanner class to read the contents of the text file we created.


Example

import java.io.File; //import the File class
import java.io.FileNotFoundException;    //import this class to handle errors
import java.util.Scanner;  //import the scanner class to read text files
 
public class ReadFile {
       public static void main (String args[]){
              try {
                     File myFile = new File("filename.txt");
                     Scanner myReader = new Scanner(myFile);
                     while(myReader.hasNextLine()){
                           String data = myReader.nextLine();
                           System.out.println(data);
                     }
                     myReader.close();
              } catch (FileNotFoundException e){
                     System.out.println("An error occured");
                     e.printStackTrace();
              }
       }
}

Output

SparkDatabox is one of the best online training institute

Note: There are many available classes to read and write files in Java such as FileReader, BufferReader, Files, Scanner, FileInputStream, FileWriter, BufferWriter, FileOutputStream, etc. Which one to use totally depends on the Java version we are working with and whether we need to read bytes or characters and the size of the file/lines etc.