error while using try with resources in Java

brain storm picture brain storm · Nov 22, 2013 · Viewed 15.5k times · Source

I have this method where I am using try with resources of Java SE 7.

private void generateSecretWord(String filename){

        try (FileReader files = new FileReader(filename)){
            Scanner input = new Scanner(files);
            String line = input.nextLine();
            String[] words = line.split(",");
            Collections.shuffle(Arrays.asList(words));
            if (words[0].length()>1){
                secretWord = words[0];
                return;
            }

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        finally {
            if (files!=null) files.close(); 
        }

    }

I get compile error in finally block that files cannot be resolved to a variable I have reference for files in the try with block. why do I get this error and how to fix it?

Thanks

Answer

kosa picture kosa · Nov 22, 2013

When you are using try with resources you don't need to explicitly close them. try-with-resources will take care of closing those resources.

Based on try-wtih-resource document

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement.