Java Tutorial Series - How to read a text file

We can read a text file using few Java libraries, in this tutorial we will learn how to do it.

How to Read a text file using Java -

Firstly, copy the path of the text file.

public class App {
   public static void main(String[] Args) throws FileNotFoundException{
       String filename = "C:\users\some_text_file.txt";
// Windows machine either accepts / or \\ 

File textFile = new File(filename);

Scanner in = new Scanner(textFile) 

While(in.hasNextLine()) {

String line = in.nextLine();
System.out.println(line);


}
in.close();
}
}

That's it!!! and that's the easiest way to read a text file using scanner class. You can modify the code as per your needs.

How to Read a file using FileReader -

public class App {

    public static void main(String[] Args) {

    File file = new File("test.txt");
    BufferedReader br = Null;  

try {
   FileReader fr = new FileReader(file);
   br = new BufferedReader(fr);
   String line;
   While( line=br.ReadLine() ! = Null) {
         System.out.println(line);
      }
}
 catch(FileNotFoundException e) {
     System.out.println("File not Found: " + file.toString());
}
catch(IOException e) {
System.out.println("unable to read file: "+ file.toString());
}
finally {
try {
br.close();
}
catch(IOException e) {
System.out.println("Unable to close file: "+ file.toString() ) ;
}
catch(NullPointerException e) {
}
}


The above method can be simplified using Java 7, we don't need to use boilerplate code. Let's look into optimised code in upcoming articles.




Happy Learning and happy sharing!!

Comments

Popular posts from this blog

Azure Tutorials Series - Azure Networking

Testing in CI/CD

Azure Tutorials Series - IaaS vs PaaS vs SaaS