Close, destructor and finalize: Java conflict
See English answers > why does a try / catch block create new variable scope? 5
try { FileInputStream in = new FileInputStream(filename); BufferedReader reader=new BufferedReader(new InputStreamReader(in)); String line; while((line=reader.readLine())!=null){ // read the file } } catch (Exception e) { System.out.println(e); }
But if I try to add the command as close, I get an error after reading the file:
in.close(); Error:(131,9) java: cannot find symbol symbol: variable in location: class ReadFile
I searched for cleaning objects after use and need to close the file before the program ends And found several posts on Java, but many are very contradictory The point is, in the end, I was very confused
Am I wrong, or is java programming a little vague and confusing? I mean, it's obvious that destructor is not really used, the use of finalize is very questionable, and the use of close is also considered unnecessary Some posts on these issues are contradictory and inconclusive
So, how to continue here? How can I get rid of this error message when I really need to close the file? Is it really unnecessary and unnecessary to close files? How to clean up class instances for program completion?
Solution
You receive an error because you define a variable inside the try block, so it is not visible anywhere except catch / finally / or try Try moving the statement outside:
Change this
try { FileInputStream in = new FileInputStream(filename);
to
FileInputStream in = null; try { in = new FileInputStream(filename);