简体   繁体   中英

getting a “^M” after each line in unix from a java created file

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?

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"); .

^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.

* nix使用\\ n作为换行符,Windows使用\\ r \\ n并在vi中生成^ M字符等。

您可能想尝试通过* nix中的dos2unix实用程序运行该文件,它将摆脱^M

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM