Read File in Java



In java programming, file read is very simple.The below code used to read the file in java programming.







Example-1
import java.io.*;
import java.util.*;

public class Main
{
      public static void main(String[] args) 
      {
          try
          {
                File object = new File("file_name.txt");

                Scanner file_reader = new Scanner(object);

                while(file_reader.hasNextLine())
                {
                      String s = file_reader.nextLine();

                      System.out.print(s);
                }

                file_reader.close();
           }   

           catch (Exception e) 
           {
                 return;
           }
      } 
}


Output



c c++ java python




Download the code







Example-2
import java.io.*;
import java.util.*;

public class Main
{
      public static void main(String[] args) throws Exception
      {
            try
            { 
                  BufferedReader read_file = new BufferedReader(new FileReader("file_name.txt"));          

                  String s;

                  while((s=read_file.readLine())!= null)
                  {
                      System.out.println(s);
                  }

                  read_file.close();
            }
            
            catch(Exception e)
            {
                   return;
            }
       } 
}


Output:



c c++ java python




Download the code