Here is an example code assuming *Nix environment.
public class TestConsole { public static void main(String[] args) { String nixSampleLine = "Line 1 \n Line 2 \n Line 3"; String[] lines = nixSampleLine.split("\\r?\\n"); for (String line : lines) { System.out.println(line); } } }Here is the output:
Line 1 Line 2 Line 3Notice the output lines are not trimmed.
Here is an example code assuming Windows environment.
public class TestConsole { public static void main(String[] args) { String winSampleLine = "Line 1 \r\n Line 2 \r\n Line 3"; String[] lines = winSampleLine.split("\\r?\\n"); for (String line : lines) { System.out.println(line); } } }Here is the output:
Line 1 Line 2 Line 3Notice the output lines are not trimmed.
Here is an example of Splitting a string using new line but also trimming each element.
public class TestConsole { public static void main(String[] args) { String winSampleLine = "Line 1 \r\n Line 2 \r\n Line 3"; String[] lines = winSampleLine.split("\\s*\\r?\\n\\s*"); for (String line : lines) { System.out.println(line); } } }
As you could see, I modified the regular expression ( \r?\n) . I added a sequence of zero or more white space (\s*) both on the left and on the right.
Here is the output.
Line 1 Line 2 Line 3