how to close a stream in a try/catch block
I have written a method to compare two file:
-----------------------------------------------------------------
public static boolean compareFile(File file1, File file2) {
BufferedInputStream in1, in2;
try {
in1 = new BufferedInputStream(new FileInputStream(
file1));
in2 = new BufferedInputStream(new FileInputStream(
file2));
int i;
while ( (i = in1.read()) != -1) {
if (i != in2.read()) {
in1.close();
in2.close();
return false;
}
}
if (in2.read() != -1) {
in1.close();
in2.close();
return false;
}
in1.close();
in2.close();
return true;
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
//in1.close(); // compile error:might not been initialized
//in2.close();
}
//in1.close(); // compile error:might not been initialized
//in2.close();
return false;
}
----------------------------------------------------------------
I can't put the in1.close() into the finally block
the compiler say" variable in1 might not have been initialized"
so I must write it three times before every return sentence
it's so bothering...do you have any better idea?
and it still have a problem
when it catch a exception,it will not reach the in1.close()
so when it bring on exception the stream can't be closed
Thank you very much in advance
: )