Does java have an equivalent to the C# “using” clause

后端 未结 12 1385
温柔的废话
温柔的废话 2020-12-29 23:09

I\'ve seen reference in some C# posted questions to a \"using\" clause. Does java have the equivalent?

12条回答
  •  -上瘾入骨i
    2020-12-29 23:34

    Yes, since Java 7 you can rewrite:

    InputStream is1 = new FileInputStream("/tmp/foo");
    try{
    
        InputStream is2 =  new FileInputStream("/tmp/bar");
        try{
             /* do stuff with is1 and is2 */
    
        } finally {
            is2.close();
        }
    } finally {
        is1.close();
    }
    

    As

    try(InputStream is1 = new FileInputStream("/tmp/foo");
        InputStream is2 =  new FileInputStream("/tmp/bar")) {
             /* do stuff with is1 and is2 */
    }
    

    The objects passed as parameters to the try statement should implement java.lang.AutoCloseable.Have a look at the official docs.

    For older versions of Java checkout this answer and this answer.

提交回复
热议问题