Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

close, destructor and finalize: Java contradictions [duplicate]

I have the following code, which works nicely in my class reading a file line by line.

 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 close, for after the file was finished reading, then I got the error:

    in.close();

Error:(131, 9) java: cannot find symbol
symbol:   variable in
location: class ReadFile

I searched about cleaning objects after use and the need to close files before your program ends. And found several posts on this for Java, but many are very contradictory. The point is that in the end I just get very confused.

Am I wrong, or Java programming is a little bit fuzzy and messy? I mean, there is apparently no real use of destructor, the use of finalize is very questionable, and the use of close is also suggested as unnecessary. Some of the posts on these issues are contradictory and non-conclusive.

So, how to proceed here? In the case I really need to close the file, how to get rid of this error message? Is it really dispensable and unnecessary to close files? What about cleaning up class instances for the the program finishes?

like image 399
Emma Yazzie Avatar asked Dec 18 '25 04:12

Emma Yazzie


1 Answers

You are getting the error because you have defined variable in inside the try block, so it is not visible in catch/finally/or anywhere outside that try. Move the declaration outside try:

Change this

try {  FileInputStream in = new FileInputStream(filename);

to

FileInputStream in = null;
try {  in = new FileInputStream(filename);
like image 197
Juned Ahsan Avatar answered Dec 20 '25 20:12

Juned Ahsan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!