Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

do i need call close() on every new inputstream?

here is the code.

public static void main(String[] args) throws IOException {

    FileInputStream fis = null;

    fis = new FileInputStream(new File("D:\\za180s.ser"));
    // do something
    fis = new FileInputStream(new File("D:\\za185s.ser"));
    // do something
    fis = new FileInputStream(new File("D:\\za186s.ser"));
    // do something
    fis = new FileInputStream(new File("D:\\za187s.ser"));
    // do something
    fis.close();

}

the problem is : need i call fis.close() method after every "do something" or i just call fis.close() once after all.

ignore whether the close() position in finally and the code need try catch or not.

thx all.

like image 205
nori Avatar asked Nov 04 '25 06:11

nori


1 Answers

Yes, you need to call close on each individual InputStream. The problem with your code is that you're reassigning the variable fis each time you create a new stream. In other words: fis no longer points to the old InputStream, so calling close will not close the previous stream.

For more information, check https://stackoverflow.com/a/40523/8819761

What you could also do is use Java 7's try-with-resources syntax, which will auto-close the stream once you exit the try block:

try (InputStream fis = new FileInputSteam(yourFile)) {
  // Do something
}

try (InputStream fis = new FileInputSteam(yourFile)) {
  // Do something else
}
like image 110
Jeroen Steenbeeke Avatar answered Nov 06 '25 21:11

Jeroen Steenbeeke