7
votes

I'm interested in simple line processing.

7
In this newer, related question there's a good intro to JDK's built-in file IO classes: stackoverflow.com/questions/19430071/…Jonik

7 Answers

8
votes

Scanner:

for(Scanner sc = new Scanner(new File("my.file")); sc.hasNext(); ) {
  String line = sc.nextLine();
  ... // do something with line
}
7
votes

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.

4
votes

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();
}
2
votes

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.

1
votes

Apache commons is always a good place to start.

See http://commons.apache.org/io/

1
votes

You could try apache's FileUtils. methods like

for(String line: FileUtils.readLines(file)) {
   System.out.println(line);
}
0
votes

You can also use InputStreamReader (which you create using an InputStream like FileInputStream) wrapped in a BufferedReader for simple line reading of file.