Date: 2012apr10
Update: 2025oct11
Language: Java
Q. Java: Nice way to split a String into lines
A. Use the split() method as shown in this full example:
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.File;
import java.nio.charset.StandardCharsets;
class Demo {
// Read a file ignoring the lines
static String readFile(final String filename) throws Exception {
InputStream is = new FileInputStream(new File(filename));
final int n = is.available();
byte [] bytes = new byte[n];
is.read(bytes, 0, n);
return new String(bytes, StandardCharsets.UTF_8);
}
public static final void main(String[] args) throws Exception {
final String fileContents = readFile("/etc/services");
for (String line : fileContents.split("\\r\\n|\\n")) { // <-- HERE
System.out.println(line);
}
}
}
Output:
# /etc/services:
# $Id: services,v 1.49 2017/08/18 12:43:23 ovasik Exp $
#
# Network services, Internet style
# IANA services version: last updated 2021-01-19
...
This works with Linux, Windows and Mac (Unix) line endings.