How to read a file line by line in Java? BufferedReader Example (original) (raw)
Hello Java Programmers, if you are looking for a way to read a file line by line in Java then don't worry, Java provides java.io package in JDK API for reading File in Java from File system e.g. C:\ or D:\ drive in Windows or any other directory in UNIX. First, you can use FileInputStream to open a file for reading. FileInputStream takes a String parameter which is a path for the file you want to read. Be careful while specifying File path as path separator is different on Window and UNIX. Windows uses backslash while UNIX uses forward slash as a path separator.
By the way, Java supports forward slash in Windows, It means if use forward slash your program will work on both Windows and UNIX. Alternatively, you can also get a PATH separator from System property path.separator. In this Java tutorial, we will code an example of How to read Files line by line using BufferedReader in Java.
How to read a text file line by line in Java
In this Java sample, we will read a text file from C:\ drive in Windows machine but since Java is platform-independent and we have used PATH separator as a forward slash, it should work on any other UNIX based system e.g. Linux, Solaris, or IBM AIX. This is the most simple and standard way of reading the file in Java.
Java Program to read a text file line by line - Example
/**
*
* Java program to demonstrate how to read text files in Java.
* Java API provides FileInputStream to open file for reading.
* for improved performance it's advised that use Reader for reading contents
* By using InputStreamReader you can convert an InputStream into Reader.
* BufferedReader provides better performance while reading files in Java.
* @author jdk67.blogspot.com
*/
public class FileReaderExample {
public static void main(String args[]) {
try {
//opening file for reading in Java
FileInputStream file
= new FileInputStream("C:/test.txt");
BufferedReader reader
= new BufferedReader(new InputStreamReader(file));
//reading file content line by line
String line = reader.readLine();
while(line != null){
System.out.println(line);
line = reader.readLine();
}
} catch (FileNotFoundException ex) {
Logger.getLogger(CollectionTest.class.getName())
.log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(CollectionTest.class.getName())
.log(Level.SEVERE, null, ex);
}
}
}
Output:
Java programming language has excellent support for File IO.
Java API provides several ways to read files from FileSystem.
From Java 7 onwards a new File API has been introduced which provides more features and improved performance.
If you look at this program, we have first opened FileInputStream pointing to file ("C:/test.txt") and then later read it.That's all on How to read Files in Java.
Related Java Tutorials