Do I have to close FileInputStream?

后端 未结 8 727
广开言路
广开言路 2021-01-07 16:43

I am working as a trainee in Test Automation. I am working with creating Junit code with Eclipse and run using Eclipse. In that I am retriving the datas from excel sheet usi

相关标签:
8条回答
  • 2021-01-07 17:27

    Yes! you should always release the resources once after you are done with them. Java has a powerful mechanism for Garbage Collection(note that it is different thing compare to resource management/leaks.) So a Garbage collector can not determine that if you need the resource in future or not? Failing to release resources may cause issues like- Denial of services, poor performance .

    As already answered but another effort less way is try with resources

        try (FileInputStream fi = new FileInputStream("c:\\search.xls")) {
    
             //do something with fi.
             //fi.getChannel() ;
    
        } catch(IOException e) {
            // exception handling.
        } finally {
        // some statements for finally.
       }
    

    Now you don't need to explicitly call fi.close() method.

    0 讨论(0)
  • 2021-01-07 17:29

    It's always a good idea to close resources you use, BUT:

    If you use resource A in resource B, it's sensible to close B instead of A if it has a method for it.

    In your case, you use FileInputStream in Workbook, so you'd better to close Workbook and rely on Workbok that it will close FileInputStream.

    In this particular case, actually, Workbook will close FileInputStream at the end of the getWorkbook() method but it's still a good idea to close Workbook to be able to be garbage collected.

    0 讨论(0)
提交回复
热议问题