Java Try With Resources Does Not Work For Assignment?

自古美人都是妖i 提交于 2019-12-11 02:24:45

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/19351410/java-try-with-resources-does-not-work-for-assignment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!