2

好的,所以我只是在编写一个快速课程,我尝试使用资源尝试而不是 try-catch-finally(讨厌这样做)方法,并且我不断收到错误“Illegal start of type”。然后我转向了关于它的 Java 教程部分:http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html它表明您可以在括号中分配一个新变量。我不确定发生了什么。

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

1 回答 1

12

这不是 try-with-resources 的工作方式。你只需要在OutputStream那里声明。所以,这会起作用:

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

try-with-resources的全部意义在于管理资源本身。他们的任务是初始化他们需要的资源,然后在执行离开范围时关闭它。因此,使用在 else where 声明的资源是没有意义的。因为关闭它没有打开的资源是不对的,然后旧的try-catch的问题又回来了。

该教程的第一行清楚地说明了这一点:

try-with-resources 语句是声明一个或多个资源的 try 语句。

...并且声明不同于初始化赋值

于 2013-10-13T23:17:01.197 回答