【问题标题】:Java Try With Resources Does Not Work For Assignment?Java Try With Resources 不适用于分配?
【发布时间】:2013-10-13 23:15:01
【问题描述】:

好的,所以我只是在编写一个快速类,我尝试使用资源尝试而不是 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);
        }
    }
}

【问题讨论】:

  • 是的,我使用的是 Java 7,上次检查时,一个真正的、善意的问题绝不是愚蠢的。

标签: java file io try-catch try-with-resources


【解决方案1】:

这不是 try-with-resources 的工作方式。您只需在此处声明OutputStream。所以,这会起作用:

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

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

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

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

... 和 declaration 不同于 initializationassignment

【讨论】:

    猜你喜欢
    • 2013-07-21
    • 1970-01-01
    • 2017-02-13
    • 1970-01-01
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多