Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Try With Resources Does Not Work For Assignment?

Alright, so I was just writing a quick class and I tried to use the try with resources instead of the try-catch-finally (hate doing that) method and I keep getting the error "Illegal start of type". I then turned to The Java Tutorials section on it: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html and it showed that you can assign a new variable in the parenthesis. I'm not sure what is going on.

private static final class EncryptedWriter {

    private final Path filePath;
    private FileOutputStream outputStream;
    private FileInputStream inputStream;

    public EncryptedWriter(Path filePath) {
        if (filePath == null) {
            this.filePath = Paths.get(EncryptionDriver.RESOURCE_FOLDER.toString(), "Encrypted.dat");
        } else {
            this.filePath = filePath;
        }
    }

    public void write(byte[] data) {
        try (this.outputStream = new FileOutputStream(this.filePath.toFile())){

        }   catch (FileNotFoundException ex) {
            Logger.getLogger(EncryptionDriver.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
like image 927
Sarah Szabo Avatar asked Dec 03 '25 04:12

Sarah Szabo


1 Answers

This is not how try-with-resources work. You have to declare the OutputStream there only. So, this would work:

try (FileOutputStream outputStream = new FileOutputStream(this.filePath.toFile())){

The whole point of try-with-resources is to manage the resource itself. They have the task of initializing the resource they need, and then close it when the execution leaves the scope. So, it doesn't make sense for it to use the resource declared else where. Because it wouldn't be right to close the resource which it hasn't opened, and then the issue with the old try-catch is back.

The very first line of that tutorial clearly states this thing:

The try-with-resources statement is a try statement that declares one or more resources.

... and declaration is different from initialization or assignment.

like image 90
Rohit Jain Avatar answered Dec 04 '25 16:12

Rohit Jain



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!