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

nor*_*ori 1 java 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();

}
Run Code Online (Sandbox Code Playgroud)

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.

Jer*_*eke 7

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 /sf/answers/2836641/

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
}
Run Code Online (Sandbox Code Playgroud)