有这样一种读取文件并做一些事情的方法:
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?
}
请看我在test
方法中的注释,可以吗?
最佳答案
至少在 LINUX 中是可能的,尽管在 Java 中不是直接的。
LINUX 有一个名为 lsof
的实用程序,可以判断给定文件是否在某个进程中打开。您可以使用 Runtime.exec 或 ProcessBuilder 调用此实用程序。
在 Windows 中,我不确定,但是你不能尝试打开文件进行写入吗?如果仍然有人打开该文件,它应该不起作用。
关于java - 是否可以检查 FileInputStream 是否正在使用文件,并且该流是否尚未关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20237905/