1

There is such a method which read a file and do something:

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
}

Now I want to test the method to make sure if any input stream that uses the file is closed or not finally.

My test code:

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?
}

Please see my comment in the test method, is it possible?

Freewind
  • 193,756
  • 157
  • 432
  • 708
  • You may be looking for a `FileChannel.lock` [here](http://stackoverflow.com/a/128168/823393) or [here](http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#lock%28%29) might help. – OldCurmudgeon Nov 27 '13 at 09:09
  • 1
    Rather than writing an elaborate and probably fallible detection system, it seems to me that what you really need is a close in a finally block. – user207421 Nov 27 '13 at 12:09

2 Answers2

1

It is possible at least in LINUX, though not directly in Java.

LINUX has a utility called lsof that can tell whether a given file is open in some process. You can call this utility with Runtime.exec or ProcessBuilder.

In Windows, I'm not sure, but couldn't you try to open the file for writing? It should not work if there is still someone having that file open.

Ingo
  • 36,037
  • 5
  • 53
  • 100
1

To make this testable, you should pass in an InputStream instead of a File.

That way you can either close the InputStream yourself, or write a test that passes in a mock InputStream and verifies that the method closed it.

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();
}
Christoffer Hammarström
  • 27,242
  • 4
  • 49
  • 58