简体   繁体   English

Java FileInputStream 在 Windows 和 Linux 中表现出不同的行为

[英]Java FileInputStream exhibits different behaviour in Windows and Linux

I came across a strange issue when writing unit tests for cross-platform Java applications, specifically using the FileInputStream.我在为跨平台 Java 应用程序编写单元测试时遇到了一个奇怪的问题,特别是使用 FileInputStream。 This test was originally written in Windows and passed此测试最初是在 Windows 中编写并通过的

        FileInputStream inputStream = new FileInputStream(file.getAbsolutePath());
        FileOutputStream outputStream = FileUtils.getFileOutputStream(file.getAbsolutePath());

        outputStream.write('a');
        outputStream.close();


        Assert.assertEquals(inputStream.read(), 'a');

This works perfectly in Windows but fails in Ubuntu as inputStream returns -1 (which is EOF)这在 Windows 中完美运行,但在 Ubuntu 中失败,因为inputStream返回 -1(即 EOF)

However if I reassign inputStream after I close outputStream like so,但是,如果我在像这样关闭outputStream后重新分配inputStream

        FileInputStream inputStream = new FileInputStream(file.getAbsolutePath());
        FileOutputStream outputStream = FileUtils.getFileOutputStream(file.getAbsolutePath());

        outputStream.write('a');
        outputStream.close();

        inputStream = new FileInputStream(file.getAbsolutePath());

        Assert.assertEquals(inputStream.read(), 'a');

everything works fine in Ubuntu and Windows.在 Ubuntu 和 Windows 中一切正常。

My guess is that it has to do with the different file systems used by Windows and Ubuntu but I was hoping someone could elaborate further.我的猜测是它与 Windows 和 Ubuntu 使用的不同文件系统有关,但我希望有人能进一步详细说明。

note: The FileUtils class is custom but works correctly.注意: FileUtils 类是自定义的,但工作正常。 I checked that the file was being written to in both OS's manually我检查了文件是否正在手动写入两个操作系统中

On windows, while a file is opened it cannot be deleted, nor the directory it is in etc. The FileOutputStream can only truncate the file, it cannot delete and replace it.在windows上,打开文件时不能删除,也不能删除它所在的目录等。 FileOutputStream只能截断文件,不能删除和替换它。 On Unix, the file lives independently of the directory structure.在 Unix 上,文件独立于目录结构。 It can be open, read and written to even if it no longer appears in any directory.即使它不再出现在任何目录中,它也可以被打开、读取和写入。 This means that FileOutputStream can delete the file and re-create it rather re-use the existing inode.这意味着 FileOutputStream 可以删除文件并重新创建它,而不是重新使用现有的 inode。

The difference is whether the file is truncated or replaced.区别在于文件是被截断还是被替换。 On Linux a file can be replaced even if it is open, on Windows it cannot.在 Linux 上,即使文件处于打开状态,也可以替换,而在 Windows 上则不能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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