Wednesday, July 8, 2009

Reading a String line by line

Given a string that isn't too long, What are the ways read it line by line?

Method 1:

BufferedReader reader = new BufferedReader(new StringReader());
reader.readLine();

Method 2:

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

Method 3:

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


Method 4:

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

No comments: