标签: try-with-resources

格式化 try-with-resources 的代码约定是什么?

我想知道用资源格式化 try 块的代码约定是什么,尤其是多个资源。目前我将每个资源放在自己的行上,以分号结尾,并使用 vim 的缩进级别(2 个制表符),如下所示:

try (
        InputStream in1 = ...;
        InputStream in2 = ...;
    ) {
    ...;
}
Run Code Online (Sandbox Code Playgroud)

我还看到人们使用分号作为分隔符而不是终止符,并且只在每个资源之间使用换行符,如下所示:

try (InputStream in1 = ...;
    InputStream in2 = ...) {
    ...;
}
Run Code Online (Sandbox Code Playgroud)

什么是公约?

java readability indentation java-7 try-with-resources

3
推荐指数
1
解决办法
1896
查看次数

使用 try-with-resources 关闭 Closeable

我有一个Map<Key, Closeable>,如果从地图上删除了一个键,我想关闭该Closeable。通常我有类似的东西:

Closeable c = map.remove(key);
c.close();
Run Code Online (Sandbox Code Playgroud)

我的 Eclipse 警告我“资源 'c' 应该由 try-with-resource 管理”,那么编写以下内容是否更好?

try (Closeable c = map.remove(key)) {}
Run Code Online (Sandbox Code Playgroud)

在我的特殊实现中,我有一个 的子类Closeable,其中close()不会抛出IOException,因此不需要异常处理。

java try-with-resources autocloseable

3
推荐指数
1
解决办法
9856
查看次数

如何将 ByteArrayOutput 流写入 groovy 中的文件?

在Java中,我可以轻松地使用以下代码将a写入ByteArrayOutputStream文件。但是,try-with-resources在 Groovy 中不起作用:(

ByteArrayOutputStream byteArrayOutputStream = getByteStreamMethod();
try(OutputStream outputStream = new FileOutputStream("thefilename")) {
    byteArrayOutputStream.writeTo(outputStream);
}
Run Code Online (Sandbox Code Playgroud)

我一直在尝试关注http://mrhaki.blogspot.co.uk/2009/11/groovy-goodness-readers-and-writers.html等链接 ,所以在这里回答IntelliJ 错误 - java: try-with-resources 是-source 1.6 错误中不支持。即使在项目设置中选择了 1.7 JDK

但我无法想到 Groovy 语法,可以将上面的 java 代码块编写为。您能在这里稍微指导一下如何在 Groovy 中编写上面的 java 代码块吗?

PS:我使用的是Groovy v2.4.12

groovy fileoutputstream bytearrayoutputstream try-with-resources

3
推荐指数
1
解决办法
8080
查看次数

由编译器完成的 Java try-with-resource 实现

我想知道,当发生异常时,try with resource 语句如何在进入 catch 块之前设法关闭资源。当异常发生时,执行立即跳转到 catch 块。所以实际上 try-with-resource 关闭资源的地方。

为了更好地理解它是如何工作的,我决定看看编译器是如何实现它的。我编写了以下代码并编译了它。

public class Test
{
    public static void main(final String[] args) {
       //I used same JDK for compilation and execution.
        System.out.println("Java version: " + System.getProperty("java.version") + "\n");
        try(CloseMe me = new CloseMe(); 
                CloseMeToo meToo = new CloseMeToo()){
                
                System.out.println("trying");
                throw new Exception("try failed");

            } catch(Exception e) {
                System.out.println("failed");
                System.out.println("\n");
                System.out.println(e.getMessage());
                System.out.println(e.getSuppressed()[0].getMessage());
                System.out.println(e.getSuppressed()[1].getMessage());
            }
    }
}

class CloseMe implements AutoCloseable {
    @Override
    public void close() throws Exception {
        System.out.println("me closing!");
        throw new …
Run Code Online (Sandbox Code Playgroud)

java try-with-resources

3
推荐指数
1
解决办法
70
查看次数

Java 18+ 是否已弃用 try-finally ?

JEP 421在即将发布的 Java 18 中发布,不赞成终结。我理解这意味着该finalize()方法已被弃用。然而,它还提到了该try/finally块并提到了 try-with-resources 作为替代方案,所以我很困惑 - 这是说 try/finally 将被弃用吗?我们是否应该开始更改遗留代码以用 try-with-resources 替换 try/finally ?

我以为这个 JEP 只是关于finalize()方法,但是互联网上的一些页面(例如https://metebalci.com/blog/what-is-new-in-java-18/)说 try/finally 是被弃用,这听起来有点令人担忧。

java try-finally try-with-resources

3
推荐指数
1
解决办法
919
查看次数

遇到"尝试资源"的问题

要澄清:由于来自Eclipse的消息,我甚至无法编译.第一个代码段:input并且inputBuffer无法识别.第二个代码片段,Eclipse希望我将交换机"Compliance and JRE切换到1.7"

我是资源尝试的新手,我不太了解语法或我做错了什么.这是我的代码

try {
   FileReader input = new FileReader(this.fileName);
   BufferedReader  inputBuffer = new BufferedReader (input);

   String line;
   while ((line = inputBuffer.readLine()) != null) {
       String[] inputData = line.split(",");

        Node<Integer> newNode = new Node<Integer>(Integer.parseInt(inputData[0]),
                                                  Integer.parseInt(inputData[1]));
        this.hashMap.add(newNode);
   }

//inputBuffer.close();
//input.close();

}catch (NumberFormatException nfe){
    System.out.println(
         "Repository could not load data due to NumberFormatException: " + nfe); 
}catch (FileNotFoundException fnfe) {
    System.out.println("File not found, error: " + fnfe);
}finally { 
    inputBuffer.close();
    input.close();
}
Run Code Online (Sandbox Code Playgroud)

finally块不起作用,所以我想试试

try (FileReader input …
Run Code Online (Sandbox Code Playgroud)

java try-with-resources

2
推荐指数
2
解决办法
7000
查看次数

Java尝试使用资源不适用于分配?

好吧,所以我只是写了一个快速的类,我试图使用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)

java io file try-catch try-with-resources

2
推荐指数
1
解决办法
4413
查看次数

尝试用资源执行最后在捕获之前阻塞吗?

我了解了Java 7功能try with resources

在catch块中,我应处理try(通常)和来自的异常finally

这是否意味着在catch之前最后调用了它?如果我想在可捕获的资源中处理该怎么办?

有一个观察,证实了我的假设。

如果try块抛出异常1,而资源的关闭方法抛出异常2,则异常1将被捕获,异常2将被抑制。

java try-catch java-7 try-with-resources

2
推荐指数
1
解决办法
7551
查看次数

try with resources子句中的异常

class Demo
{
    public static void main(String args[]) throws java.io.IOException
    {
        try(FileInputStream fin = new FileInputStream("Demo.txt"))
        {
            //This block is executed successfully
        }

        System.out.println("Will it be executed if error occurs in try clause");
    }
}
Run Code Online (Sandbox Code Playgroud)

假设代码中的代码try block执行成功,有些代码exception发生try with resource clause,这意味着auto closing文件中发生了异常.

将如何处理该异常try with resource clause

我想问的是,该异常会被抛到JVM并且会突然终止我的程序并且该println语句不会被执行吗?

我可以捕获该异常,以便还可以执行剩余的程序吗?

java ioexception try-with-resources

2
推荐指数
1
解决办法
1296
查看次数

为什么抑制try-with-resource的异常以相反的执行顺序处理?

在正常的try-catch-finally中,像这样,

try {
    throw new ExceptionA();
} finally {
    throw new ExceptionB();
}
Run Code Online (Sandbox Code Playgroud)

ExceptionA在Exception B之前抛出.ExceptionA将被禁止.

但是在try-with-resource中,像这样,

try ( // declare resource that throw ExceptionA in close method ) {
    throw new ExceptionB();
}
Run Code Online (Sandbox Code Playgroud)

ExceptionA在ExceptionB之后抛出.ExceptionA将被禁止.

为什么他们有不同的抑制异常的命令?

java exception-handling exception try-with-resources

2
推荐指数
1
解决办法
906
查看次数