views:

976

answers:

3

The Javadoc for BufferedReader.readLine() says:

A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed.

I need slightly better control than this (e.g. I would like to be able to specify that an end of line is "\r\n", so that an "\n" by itself does not terminate the line).

Is there any JDK or library function which does this?

A: 

I don't know of any standard API that would acomplish this.

It's possible to simple read in the WHOLE file into a String and then split it at your desired ending character.

for(String line: testFile.split("\r\n")){
...
}
cb0
Unfortunately our files are generally going to be far too large for this to work.
Simon Nickerson
+6  A: 

Try using the Scanner class:

String line = Scanner(file).useDelimiter("\r\n").next();

Greg Noe
Great! This looks like exactly what I need. Thanks.
Simon Nickerson
Bitter experience suggests it's worth mentioning that Scanner uses an Iterator-style API (hasNext/next), and throws NoSuchElementException rather than returning null when there's no more input
Martin McNulty
+1  A: 

Depending on what the use case for which you need the BufferedReader, you can maybe change over to using the Scanner class, which is able to read text from different sources (files, streams), and has a direct method th specify the delimiting pattern. See http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html#useDelimiter(java.lang.String)

Juve