Madhesh Madhesh - 3 months ago 15
Linux Question

Unable to add new line in input file using linux machine

My requirement is to generate a text file.I added the new line in my file using bufferedWriter.newLine() its working fine in windows but its not working in linux.
I tried too many things but nothing is worked out so for.If i open the generated text file in notepad++ its show as line separated but in notepad it looks with out any line separator.In the console i can find the new line in both the platform but the file only windows has the new line but not in linux.

Below is my code

File file = new File(fileToWrite);
bufferedWrtier = new BufferedWriter(new FileWriter(file));
LOGGER.debug("Line Separator 1:: "+System.getProperty("line.separator"));
LOGGER.debug("Line Separator 2:: "+System.lineSeparator());
LOGGER.debug("Line Separator 3:: "+SystemUtils.LINE_SEPARATOR);

Any help will be greatly appreciated!!!!!!!!!!

Local Machine Os: windows
Server Machine Os: Linux


What you're seeing here is a difference in newline representation, based on the OS you're using.

There are two control characters you need to know:

  • CL - carriage return ('\r' or 0x0D in hex)
  • LF - line feed ('\n' or 0x0A in hex)

Windows natively uses the CL+LF combination for newlines (\r\n combination, or two bytes) while Linux uses only LF (\n, one byte).

Notepad is a pretty limited tool and it can correctly interpret only the Windows combination - if it sees a sequence of two bytes - 0x0D followed by 0x0A in your file, it will display that as a new line.

If it only sees 0x0A without 0x0D, it will not treat it as a new line combination, but will display 0x0A as a box (or it will just be ignored on Windows 10), since it is a non printable character.

To see effects of this, in Notepad++, turn on viewing of all characters:

View -> Show symbol -> Show all characters

You will see that a Windows file has CRLF, while Unix-like has LF.

Unix-like will not be displayed correctly in notepad.

You can switch between Windows and Unix-like like this:

Edit -> EOL conversion

I'd suggest reading the Wikipedia article to learn more about it and a SO post to know more.