His His - 1 year ago 59
Java Question

Read String line by line in Java

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>));

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?

ftl ftl

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.