fatcodeguy
Programmer
Hi,
I have a program in which I do a lot of file reading, so I want to ensure i always close my FileInputStreams. To do this, I want to put the fis.close() statement in the finally{} block of my exception handling because the finally block is ALWAYS executed, whether an exception is caught or not (right?). So I do something like this
But I get an error message
Which makes sense, but I can't figure out how to make sure I ALWAYS close my file streams (the same thing happens with database connections conn.close()).
Can anybody help? Many thanks!
I have a program in which I do a lot of file reading, so I want to ensure i always close my FileInputStreams. To do this, I want to put the fis.close() statement in the finally{} block of my exception handling because the finally block is ALWAYS executed, whether an exception is caught or not (right?). So I do something like this
Code:
import java.io.*;
import java.lang.*;
import java.util.*;
public class Test{
//main function
public static void main (String args[]) {
//vars
String path = null;
FileInputStream fis = null;
File file = null;
try{
path = new String("V:\\sys\\crss-scrs\\20000\\3000\\800\\60\\veritas\\39788\\qa39788nssf.htm");
file = new File(path);
fis = new FileInputStream(file);
int fileSize = (fis.available());
}
catch(IOException e) {System.out.println(e.getMessage());e.printStackTrace();}
finally { fis.close();}
}//end main
}//end class
But I get an error message
Code:
Test.java:29: unreported exception java.io.IOException; must be caught or declar
ed to be thrown
fis.close();
^
1 error
Which makes sense, but I can't figure out how to make sure I ALWAYS close my file streams (the same thing happens with database connections conn.close()).
Can anybody help? Many thanks!