Reading Files
Created: 09.07.2014
Reading text files line-by-line is a common task in many programs. There are basically two efficient ways to read files line by line (as a string) in java.
Reading files the java 8 way
You can use the java 8 streaming API in combination with the java 7 file.nio:
Path sampleFile = Paths.get("sample.txt");
try {
Files.readAllLines(sampleFile)
.forEach(line -> System.out.println(line));
} catch (IOException e) {
e.printStackTrace();
}
You could call any method instead of System.out.println().
Reading files the java 7 way
You could use an ordinary foreach loop instead of the streaming API call.
Path sampleFile = Paths.get("sample.txt");
try {
for(String line: Files.readAllLines(sampleFile)){
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
The old-fashioned (deprecated) way
Both solutions mentioned above are based on java.nio.Files which creates a BufferedReader to read the files. In an old-fashioned way you would have done this "by hand":
BufferedReader br = null;
try {
String line;
BufferedReader br = new BufferedReader(new FileReader("sample.txt"));
while ((line= br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
}