Auspexis
Auspexis

Reputation: 79

How to close Java scanner when scanner is referenced in a string?

I currently have a scanner that scans the entire contents of a file and prints the data that is read to a text area, sort of like an open function. My problem is that the method that i have used (as well as being the only one i know of) requires a file to be created and then deleted, however this file that has been created cannot be deleted as it is being used by the process of the scanner and I do not know how to close the scanner as it has been defined in a string. It is probarably a simple solution, but it has been eluding me for some time. Thank you in advance. Here is my code:

int returnVal = fc.showDialog(this,
                                  "Open");

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        String fullPath = file.getAbsolutePath();

        try {
            new FileEncryptor("DES/ECB/PKCS5Padding",fullPath).decrypt();


                String content = new Scanner(new File(fullPath + ".dec")).useDelimiter("\\Z").next();

                jTextArea1.setText(content);

                //close scanner here to delete file

                File n = new File(fullPath + ".dec");
                System.out.println(n);
                n.delete();

        } catch (Exception e) {

            e.printStackTrace();
        }   


    } else {

    }

    //Reset the file chooser for the next time it's shown.
    fc.setSelectedFile(null);
}                                         

Upvotes: 1

Views: 644

Answers (3)

Malfist
Malfist

Reputation: 31805

You're losing the handle to the scanner.

Try something like:

            Scanner contentScanner = new Scanner(new File(fullPath + ".dec"));
            String content = contentScanner.useDelimiter("\\Z").next();
            contentScanner.close();

Upvotes: 0

Pace
Pace

Reputation: 43867

Break it into more lines.

Scanner scanner = new Scanner(new File(fullPath + ".dec"));
String content = null;
try {
   content = scanner.useDelimiter("\\Z").next();
} finally {
   scanner.close();
}

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533680

You can't reference an object in a String, esp not a Scanner.

The String is a copy of the data you want so closing the Scanner won't alter the String which is immutable (unchangeable)

What you want to do is hold onto the Scanner so you can close it.

Scanner scanner = new Scanner(new File(fullPath + ".dec")).useDelimiter("\\Z");
String content = scanner.nextLine();

scanner.close();

Upvotes: 0

Related Questions