Search code examples
javafilefileinputstream

Should I close the FileInputStream multiple times if reinstantiate it


Following is the code. I am doing it right by calling close only once?

public class SeatTest extends TestCase {
    FileInputStream inputStream;
    ArrayList<File> fileNames = new ArrayList<>();

    @SuppressWarnings("unchecked")
    @Override
    protected void setUp() throws Exception {
        File dir = new File("./data/test/seat_layouts");
        fileNames = new ArrayList<File>(Arrays.asList(dir.listFiles()));
    }

    @Test
    public void testParse() throws IOException {
        for (File file : fileNames) {
            inputStream = new FileInputStream(file);
            String everyThing = IOUtils.toString(inputStream, "UTF-8");
            //do something
        }
    }

    @Override
    protected void tearDown() throws Exception {
        if (inputStream != null) {
            inputStream.close();
        }
    }


}

Solution

  • Should I close the FileInputStream multiple times if reinstantiate it.

    Yes .... sort of.

    Each instance of FileInputStream should be closed or you risk leaking file descriptors. Each time you "reinstantiate" the object, you are creating a new instance, and each instance should be closed.

    For example

    @Test
    public void testParse() throws IOException {
        for (File file : fileNames) {
            try (FileInputStream inputStream = new FileInputStream(file)) {
                String everyThing = IOUtils.toString(inputStream, "UTF-8");
                //do something
            }
        }
    }
    

    Note that the try-with-resource will close the resource (i.e. inputStream) automatically.

    If you do it this way, the teardown code is not required.