比较依赖于操作系统的文件。 J单元

Comparing Files dependent on operative system. JUnit

我有一个简单的 JUnit 测试,它检查两个文件是否具有相同的内容。它在我的 Unix 笔记本电脑上工作得很好。

这是测试:

    boolean response = false;
    try {
      File got = File.createTempFile("got-", ".csv");
      String outputPath = got.getAbsolutePath();
      testedObject.createCsvFile(outputPath);
      got = new File(outputPath);
      String expectedFilePath = getClass().getClassLoader().getResource("expected.csv").getFile();
      File expected = new File(expectedFilePath);
      response = FileUtils.contentEquals(got, expected); // Here it is the key
    } catch (IOException e) {
      // Nothing to do Yay!
    }
    Assert.assertTrue(response);

之所以有效,是因为如果我手动比较两个文件,例如通过 diff 命令,它们是完全相同的。现在。
我的队友用 Windows 笔记本电脑编码,当他 运行 测试时它坏了!然后我们开始调试。

从视觉上看,两个文件是一样的;我的意思是在 human 修订版中你无法察觉到任何差异。但是如果我们在 Cwin 终端中执行: diff expected.csv got.csv 和 windows 认为每一行都不一样
测试失败了。

什么问题,是操作系统?如果那是真的,有什么方法可以比较文件内容不依赖于操作系统

我的猜测是,这很可能是由于 \n 值,在类似 unix 的软件中是 \r\n。

无论如何,查看两个文件是否具有相同内容的正确方法是对它们进行散列(即通过 sha1)并检查散列是否匹配!

此行为可归因于 Line Feed 在两个操作系统上的不同。 如果您希望它独立于平台,您应该使用

从运行时获取值
System.getProperty("line.separator");

您可能还想查看这两个文件的字符编码

这个回答可以帮助到您:Java Apache FileUtils readFileToString and writeStringToFile problems。问题的作者在谈论 PDF 文件,但这个答案对你的问题很有意义。