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

后端 未结 12 1432
温柔的废话
温柔的废话 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

    The actual idiom used by most programmers for the first example is this:

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

    There is less indenting using this idiom, which becomes even more important when you have more then 2 resources to cleanup.

    Also, you can add a catch clause to the structure that will deal with the new FileStream()'s throwing an exception if you need it to. In the first example you would have to have another enclosing try/catch block if you wanted to do this.

提交回复
热议问题