I am reading a file via the BufferedReader
String filename = ...
br = new BufferedReader( new FileInputStream(filename));
while (true) {
String s = br.readLine();
if (s == null) break;
...
}
I need to know if the lines are separated by '\n' or '\r\n' is there way I can find out ?
I don't want to open the FileInputStream so to scan it initially. Ideally I would like to ask the BufferedReader since it must know.
I am happy to override the BufferedReader to hack it but I really don't want to open the filestream twice.
Thanks,
Note: the current line separator (returned by System.getProperty("line.separator") ) can not be used as the file could have been written by another app on another operating system.
If you happen to be reading this file into a Swing text component then you can just use the JTextComponent.read(...) method to load the file into the Document. Then you can use:
to get actual EOL string that was used in the file.
After reading the java docs (I confess to being a pythonista), it seems that there isn't a clean way to determine the line-end encoding used in a specific file.
The best thing I can recommended is that you use
BufferedReader.read()
and iterate over every character in the file. Something like this:If you are using groovy, you can simply do:
BufferedReader.readLine()
does not provide any means of determining what the line break was. If you need to know, you'll need to read characters in yourself and find line breaks yourself.You may be interested in the internal LineBuffer class from Guava (as well as the public LineReader class it's used in).
LineBuffer
provides a callback methodvoid handleLine(String line, String end)
whereend
is the line break characters. You could probably base something to do what you want on that. An API might look something likepublic Line readLine()
whereLine
is an object that contains both the line text and the line end.BufferedReader
does not acceptFileInputStreams
No, you cannot find out the line terminator character that was used in the file being read by BufferedReader. That information is lost while reading the file.
Unfornunately all answers below are incorrect.
Edit: And yes you can always extend BufferedReader to include the additional functionality you desire.
Not sure if useful, but sometimes I need to find out the line delimiter after I've read the file already far-down the road.
In this case I use this code: