Sar*_*abo 2 java io file try-catch try-with-resources
好吧,所以我只是写了一个快速的类,我试图使用try资源而不是try-catch-finally(讨厌做那个)方法,我不断收到错误"非法启动类型".然后我转向它上面的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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
Roh*_*ain 12
这不是试用资源的方式.你必须在OutputStream
那里宣布.所以,这将工作:
try (FileOutputStream outputStream = new FileOutputStream(this.filePath.toFile())){
Run Code Online (Sandbox Code Playgroud)
整点的try-与资源是管理资源本身.他们的任务是初始化他们需要的资源,然后在执行离开范围时关闭它.因此,使用其他地方声明的资源是没有意义的.因为关闭它尚未打开的资源是不对的,然后旧的try-catch的问题又回来了.
该教程的第一行清楚地说明了这一点:
try-with-resources语句是一个声明一个或多个资源的try语句.
...和声明与初始化或赋值不同.
归档时间: |
|
查看次数: |
4413 次 |
最近记录: |