I'm interested in simple line processing.
7 Answers
Take a look at the Scanner class.
It was added in Java 5 to make reading strings and files far easier, than the old FileReaders and FileInputStream chains (no more new BufferedReader(new FileReader())
just to get to a readLine
method).
In the Scanner class, you can use the nextLine
method to read a line at a time, but it also has lots of util methods for finding primitives and regular expressions in the file.
You can use BufferedReader
, something like this:-
try {
BufferedReader input = new BufferedReader(new FileReader(new File("c:\\test.txt")));
try {
String line = null;
while ((line = input.readLine()) != null) {
System.out.println(line);
}
} finally {
input.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
If you're willing to make use of 3rd party libraries, then utility classes such as Files
from Guava or FileUtils
from Apache Commons IO make reading files very simple.
Examples below (where File file = new File("path/to/file.txt")
) of reading all lines of a text file into a List, and reading the whole file into a String.
Guava:
List<String> lines = Files.readLines(file, Charsets.UTF_8);
String contents = Files.toString(file, Charsets.UTF_8);
Apache Commons IO:
List<String> lines = FileUtils.readLines(file, "UTF-8");
String contents = FileUtils.readFileToString(file, "UTF-8")
My recommendation (as of 2013) is Guava, which is a modern, clean, actively maintained library. It's generally of higher quality than Apache Commons stuff.
Of course, adding Guava just for this wouldn't make sense, as it's a relatively big library. On the other hand, not using Guava in a Java project today would IMO be silly. :-)
Admittedly JDK now provides somewhat adequate tools (Scanner) for this particular purpose; using a 3rd party lib for reading files was more justified when something like this was the alternative.