4

I have a Java program that creates a file and prints a bunch of data using this statement:

out.write(data+"|"+data2+"\r\n");

When I view this file in vim in Unix I see a ^M after each line. What is it? What is causing this? How can I get rid of it?

Mike
  • 2,299
  • 13
  • 49
  • 71
  • 2
    possible duplicate of [How to convert the ^M linebreak to 'normal' linebreak in a file?](http://stackoverflow.com/questions/811193/how-to-convert-the-m-linebreak-to-normal-linebreak-in-a-file) – GWW Nov 04 '11 at 17:22

5 Answers5

8

You need to use the platform-specific line separator string instead of \r\n when constructing your output string. That can be obtained by System.getProperty("line.separator");.

Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
4

^M is character 13 (decimal) which is the carriage return (in your code it's \r). Notice that M is the 13th letter of the alphabet.

You can get rid of it by not including \r in your code. This will work fine if you're on a unix platform. On windows, the file will look funny unless you're viewing it in something like Wordpad.

Jonathan M
  • 17,145
  • 9
  • 58
  • 91
1

*nix uses \n for newline, Windows uses \r\n and produces that ^M character in vi and the like.

StrangeWill
  • 2,106
  • 1
  • 23
  • 36
1

You may want to try running the file through dos2unix utility in *nix, it will get rid of ^M

srkavin
  • 1,152
  • 7
  • 17
  • 1
    This works after the file was created. The solution that `Ted Hopp` has given would solve it when you write the file contents. – srkavin Nov 04 '11 at 17:25
0

You'll generally only see those if the first line was a unix line ending (lf) but it also includes DOS line endings. To remove them (and correct the file), load it again using :e ++ff=dos, then :set ff=unix, then write it.

Within the Java code, if you're writing text data instead of binary, use a PrintStream and use print() and println() which adds the correct line ending for your system.

Colselaw
  • 1,069
  • 9
  • 21