Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to close the fileInputStream while reading the property file

Tags:

java

I have following code :

    // Read properties file.
     Properties properties = new Properties();
     try {
     properties.load(new FileInputStream("filename.properties"));
     } catch (FileNotFoundException e) {
     system.out.println("FileNotFound");
     }catch (IOException e) {
     system.out.println("IOEXCeption");
     }

Is it required to close the FileInputStream? If yes, how do I do that? I am getting a bad practice error in my code checklist . Asking it to put finally block.

like image 555
Beginner Avatar asked Jul 11 '12 10:07

Beginner


1 Answers

You must the close the FileInputStream, as the Properties instance will not. From the Properties.load() javadoc:

The specified stream remains open after this method returns.

Store the FileInputStream in a separate variable, declared outside of the try and add a finally block that closes the FileInputStream if it was opened:

Properties properties = new Properties();
FileInputStream fis = null;
try {
    fis = new FileInputStream("filename.properties");
    properties.load(fis);
} catch (FileNotFoundException e) {
    system.out.println("FileNotFound");
} catch (IOException e) {
    system.out.println("IOEXCeption");
} finally {
    if (null != fis)
    {
        try
        {
            fis.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }
}

Use try-with-resources since Java 7:

final Properties properties = new Properties();
try (final FileInputStream fis =
         new FileInputStream("filename.properties"))
{
    properties.load(fis);
} catch (FileNotFoundException e) {
    system.out.println("FileNotFound");
} catch (IOException e) {
    system.out.println("IOEXCeption");
}
like image 110
hmjd Avatar answered Nov 04 '22 14:11

hmjd