Question

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?

Was it helpful?

Solution

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);

OTHER TIPS

you may be closing in.close() out side try block so obviously you will get error because in is defined in try block which is local.

Better to use try with resource so you need not to manually close file stream

Ideally you must call the close() method inside the finally block, after the null check. And for that you need to declare the variable in outside the try block.

Calling the close() method in finally block ensures that it is called irrespective of whether an Exception is thrown or not by the code in try block.

EDIT : This is when you are using Java 6 or earlier version. For Java 7 and higher you could use try with resource as suggested by @JqueryLearner

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top