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

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

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

12条回答
  •  情深已故
    2020-12-29 23:21

    Yes. Java 1.7 introduced the try-with-resources construct allowing you to write:

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

    ... just like a using statement.

    Unfortunately, before Java 1.7, Java programmers were forced to use try{ ... } finally { ... }. In Java 1.6:

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

提交回复
热议问题