Java 是否可以检查FileInputStream是否正在使用文件,并且该流尚未关闭?

Java 是否可以检查FileInputStream是否正在使用文件,并且该流尚未关闭?,java,testing,Java,Testing,有一种方法可以读取文件并执行某些操作: public void readFileAndDoSomething(File file) { InputStream inputStream = new FileInputStream(file); // a lot of complex code which reads the inputStream // and we don't know if the inputStream is closed or not } 现

有一种方法可以读取文件并执行某些操作:

public void readFileAndDoSomething(File file) {
     InputStream inputStream = new FileInputStream(file);
     // a lot of complex code which reads the inputStream
     // and we don't know if the inputStream is closed or not
}
现在我想测试该方法,以确保使用该文件的任何输入流是否最终关闭

我的测试代码:

public void test() {
    File testFile = new File("my_test_file");
    readFileAndDoSomething(testFile);

    // is it possible to just check the file to make sure
    // if it is still used by some unclosed input streams?
}

请参阅我在
测试
方法中的评论,这可能吗?

这至少在LINUX中是可能的,但不是直接在Java中

LINUX有一个名为
lsof
的实用程序,它可以判断给定文件是否在某个进程中打开。您可以使用Runtime.exec或ProcessBuilder调用此实用程序


在Windows中,我不确定,但您不能尝试打开文件进行写入吗?如果仍有人打开了该文件,则它不应工作。

要使该文件可测试,应传入
InputStream
,而不是
文件

这样,您可以自己关闭
InputStream
,或者编写一个测试,通过模拟
InputStream
并验证该方法是否关闭了它

public void readStreamAndDoSomething(InputStream inputStream) {
    // a lot of complex code which reads the inputStream
    // and we don't know if the inputStream is closed or not
}

public void clientCode(File file) {
    InputStream inputStream = new FileInputStream(file);
    readStreamAndDoSomething(inputStream);
    inputStream.close();
}

您可能正在寻找一个
文件通道.锁
,或者可能会有所帮助.在我看来,您真正需要的不是编写一个复杂的、可能会出错的检测系统,而是在最后一个模块中关闭。