Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get EOL character of any file in java

Tags:

java

file-io

I am trying to find the EOL character of a file. I have tried the following snippet:

java.io.FileInputStream inputStream = null;  
inputStream=new java.io.FileInputStream (inputFile.trim());
java.util.Properties p = new java.util.Properties(System.getProperties());  
p.load(inputStream);  
System.setProperties(p);  
String lineSeperator=System.getProperties().getProperty("line.separator");  
System.out.println("--"+lineSeperator);

The result i am getting here is always \r\n, Even if i am reading a Linux originated file where delimiter should be \n.

What am i doing wrong ?

like image 446
justin3250 Avatar asked Jan 23 '12 09:01

justin3250


People also ask

How do you validate a character in Java?

We can check whether the given character in a string is a number/letter by using isDigit() method of Character class. The isDigit() method is a static method and determines if the specified character is a digit.

What is the end of line character in Java?

The newline character, also called end of line (EOL), line break, line feed, line separator or carriage return, is a control character to tell the end of a line of text, and the next character should start at a new line. On the Windows system, it is \r\n , on the Linux system, it is \n . In Java, we can use System.

How can you write the systems newline character to a file in Java?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.


1 Answers

System.getProperty("line.separator") returns the default line separator of your operating system. It has nothing to do with what the line separator used by a given file is.

To find it, open the file as a character stream, and iterate over the characters until you find '\r' or '\n'. If you find '\n' first, the you have a unix file. If you find '\r' followed by '\n', you have a windows file. If you find '\r' not followed by '\n', you have an old Mac file.

This of course assumes that the file is a text file in the first place, that a single kind of EOL is used in the file, and that you know the encoding of the file. If you don't know the encoding, you might use the same algorithm and use a byte stream instead of a character stream.

Note that this is irrelevant, most of the time, since Java has APIs that read a file line by line, and handle all combinations of EOLs just fine.

like image 190
JB Nizet Avatar answered Oct 30 '22 13:10

JB Nizet