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***](https://stackoverflow.com/questions/171952/is-there-a-destructor-for-java), the use of [***finalize***](https://stackoverflow.com/questions/158174/why-would-you-ever-implement-finalize) is very questionable, and the use of [***close***](https://stackoverflow.com/questions/8211760/do-i-need-to-close-files-i-perform-file-getname-on) 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?

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

```
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