为什么用Java和AIX执行该简单程序会导致回车/换行文件不同? [英] Why this simple program leads to different carriage return/line feed file when executed in Java and AIX?
问题描述
如果我在Windows 7上然后在AIX(Unix系统)上运行此简单程序,并使用诸如Winmerge或Compare It之类的工具比较两个生成的文件,它会告诉我回车和换行符不同,但是内容相同.
If I run this simple program on Windows 7 and then on AIX (Unix system) and compare the two generated files using a tool such as Winmerge or Compare It, it tells me that the Carriage Return and Line Feed are different but the content identical.
-
那是为什么?如果在这种情况下都使用相同的编码"UTF-8",那应该不一样吗?
Why is that? Isn't supposed to be the same if both use the same encoding "UTF-8" in this case?
如何使两个文件完全相等?
How can I make both files totally equal?
public class WriteFile {
public static void main(String[] args) throws IOException {
write();
}
public static void write() throws IOException {
File file = new File("/tmp/test.txt");
file.delete();
file.createNewFile();
String str = "hello";
FileOutputStream fileOs = new FileOutputStream(file);
PrintWriter writer = new PrintWriter(new OutputStreamWriter(fileOs, "UTF-8"), true);
writer.println(str);
writer.close();
}
}
推荐答案
不同的操作系统使用不同的换行符:
Different operating systems use different newline conventions:
- 在Windows上,换行符为
CR+LF
; - 在Unix上,换行符为
LF
.
- On Windows, newlines are
CR+LF
; - On Unix, newlines are
LF
.
(如果您感到好奇,可以使用更多.)
(If you're curious, there's more.).
如果需要输出文件相同,请不要使用println()
,而应使用\n
或\r\n
代替:
If you need the output files to be identical, don't use println()
, but write \n
or \r\n
instead:
writer.printf("%s\n", str); // LF
writer.printf("%s\r\n", str); // CR+LF
这篇关于为什么用Java和AIX执行该简单程序会导致回车/换行文件不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!