1

I have a Java Application running on Linux machine, it is generating a file in which each record is separated by new line,

This file will be used by an application running on Unix SunOS system and my code below does not generate proper file . I mean following code generates a file in which each line end with ^M charater when I open it with vi editor in Unix system

bw = new BufferedWriter(new FileWriter(file));
bw.write("\n");

Which character I have to write in order to see the file properly in Unix system.

Ahmet Karakaya
  • 9,899
  • 23
  • 86
  • 141
  • 1
    Something is horribly wrong if the shown code generates a `\r\n` line ending. Are you sure you are looking at the correct file? – Henry Dec 19 '14 at 18:17
  • 2
    I suggest you use PrintWriter.println() and it will handle new lines for your. – Peter Lawrey Dec 19 '14 at 18:19
  • @Herry I copy the file from Linux to Windows ,then to Unix. Does this operation manipulate the file? – Ahmet Karakaya Dec 19 '14 at 18:29
  • 1
    @mmc18 Yes, the tool that you're using to transfer the file could change the line terminators. It depends on what tools you're using and how you're using them. – Kenster Dec 19 '14 at 18:34
  • Can I use ftp tool copy file from linux to unix, or scp? – Ahmet Karakaya Dec 19 '14 at 18:50
  • @mmc18 If you use ascii mode in ftp then it will modify line endings. If you edit the file in Windows it will also modify the line endings. In short, why go Linux > Windows > Unix? – Elliott Frisch Dec 19 '14 at 18:53
  • linux->windows->unix path is not mandotory for me, I am just explaining what I did, actually the proper way is to ftp (bin mode) file from linux to unix right? – Ahmet Karakaya Dec 19 '14 at 18:56
  • 1
    @mmc18 yes, binary mode makes sure the file is not changed. It should even work when you go via Windows (provided you don't touch the file with any Windows tools). – Henry Dec 19 '14 at 19:51

1 Answers1

5

The \n is the correct line ending for Unix. It's windows that uses \r\n as a line ending (with the \r or carriage return symbol) that looks like ^M. You can use System.lineSeparator() to get the correct line-ending for your system. You can also use dos2unix to remove dos formatted newlines from text files.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249