Java尝试使用资源不适用于分配? [英] Java Try With Resources Does Not Work For Assignment?

查看:140
本文介绍了Java尝试使用资源不适用于分配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,所以我只是写了一个快速的类,我尝试使用try资源而不是try-catch-finally(讨厌这样做)方法,并且我不断收到错误非法启动类型。然后我转向它上面的Java教程部分: http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html 它显示了你可以在括号中指定一个新变量。我不确定发生了什么。

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


推荐答案

这不是try-with-resources的工作方式。你必须在那里声明 OutputStream 。所以,这样可行:

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())){

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

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:


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

... 声明初始化不同作业

这篇关于Java尝试使用资源不适用于分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆