Skip to content
Advertisement

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.

JavaScript

File format

JavaScript

Advertisement

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():

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement