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.
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");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With