Skip to content

Java – splitting files by newline

How can I split file by newline? I’ve attempted to split by doing line.split("\r?\n") – but when I try printing the 0th index I get the entire file content when I was expecting just the first line. but if I try printing the result at index 0 I get the entire file content, when I expected to get just the first line.

FileInputStream file = new FileInputStream("file.rcp");
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
String line = reader.readLine();

 while (line != null) {
            String [] split = line.split("\r?\n");
            String name = split[0]; // test to see if name will print the first line only
            System.out.println(name);
            line = reader.readLine();
        }

File format

Food name - gyros
author - some name
Cusine type - greek
Directions - some directions
Ingredients - some ingredients

Answer

The documentation, i.e. the javadoc of readline(), says:

Returns a String containing the contents of the line, not including any line-termination characters

Which means that line.split("\r?\n") is the same as new String[] { line }, i.e. it’s an entirely useless thing to do.

If you want to read the entire file into memory as an array of lines, just call Files.readAllLines():

List<String> linesList = Files.readAllLines(Paths.get("file.rcp"));
String[] linesArray = linesList.toArray(new String[0]);