Java IOjava-io-examples

How to read a file in Java

Posted On
Posted By admin

In Java, you can use the BufferedReader class as follows in order to read a file:

 


package demo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class MyTextFileReader {

public static void main(String args[]){
try {
BufferedReader br = new BufferedReader(new FileReader(new File("F:/test.txt")));
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch ( IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

leave a Comment