views:

862

answers:

3

Given a string that isn't too long, what is the best way to read it line by line?

I know you can do:

BufferedReader reader = new BufferedReader(new StringReader(<string>));
reader.readLine();

Another way would be to take the substring on the eol:

final String eol = System.getProperty("line.separator");
output = output.substring(output.indexOf(eol + 1));

Any other maybe simpler ways of doing it? I have no problems with the above approaches, just interested to know if any of you know something that may look simpler and more efficient?

+6  A: 

There is also Scanner. You can use it just like the BufferedReader:

Scanner scanner = new Scanner(myString);
while (scanner.hasNextLine()) {
  String line = scanner.nextLine();
  // process the line
}

I think that this is a bit cleaner approach that both of the suggested ones.

notnoop
Note that in my experience Scanner is about 4x slower than String.split.
Zarkonnen
I don't think it's a fair comparison though - String.split relies on the entire input being read into memory, which isn't always feasible (e.g. for large files).
Adamski
The input has to reside in memory, given that the input is String. The memory overhead is the array. Also, the resulting Strings reuse the same back-end character array.
notnoop
+8  A: 

You can also use the split method of String:

String[] lines = string.split(System.getProperty("line.separator"));

This gives you all lines in a handy array.

I don't know about the performance of split. It uses regular expressions.

ftl
And hope the line separator doesn't have regex characters in it. :)
Tom Hawtin - tackline
"line.separator" is not reliable anyway. Just because the code is running on (e.g.) Unix, what's to stop the file from having Windows-style "\r\n" line separators? BufferedReader.readLine() and Scanner.nextLine() always check for all three styles of separator.
Alan Moore
+1  A: 

Using Apache Commons IOUtils you can do this nicely via

List lines = IOUtils.readlines(new StringReader(string));

It's not doing anything clever, but it's nice and compact. It'll handle streams as well, and you can get a LineIterator too if you prefer.

Brian Agnew