how to detect line breaks in java

If you have the data already in a String:

String[] lines = string.split("\r\n|\n|\r");
for (String line : lines) {
    System.out.println(line);
}

Or read the lines directly from a file:

BufferedReader br = new BufferedReader(new FileReader("myfilename"));
String line = null;
while ((line = br.readLine()) != null) {
    System.out.println(line);
}

Java 7+ has a convenience method to read lines directly from the filesystem:

Path path = FileSystems.getDefault().getPath("myfilename");
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
for (String line : lines) {
    System.out.println(line);
}

Java does not do automatic charset detection, so you are responsible for setting the charset correctly when reading a text file; otherwise characters may not be read correctly. Don't forget to be tidy: .close() your file handles.

Tags:

Java

Text

Newline