java是否与C#"using"子句等效

dac*_*cot 24 java syntax

我已经看到在一些C#发布的问题中引用了一个"using"子句.java有相同的功能吗?

Aar*_*paa 27

是.Java 1.7引入了try-with-resources构造,允许您编写:

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

......就像一个 using声明.

不幸的是,在Java 1.7之前,Java程序员被迫最终使用try {...} {...}.在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();
}
Run Code Online (Sandbox Code Playgroud)

  • 作为一个Java家伙,上面的比较只是一种痛苦. (2认同)

Lod*_*rds 10

是的,因为Java 7你可以重写:

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();
}
Run Code Online (Sandbox Code Playgroud)

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

作为参数传递给try语句的对象应该实现java.lang.AutoCloseable.看一下官方文档.

对于旧版本的Java,请查看此答案此答案.


Tom*_*ine 5

语言中最接近的等价物是使用try-finally.

using (InputStream in as FileInputStream("myfile")) {
    ... use in ...
}
Run Code Online (Sandbox Code Playgroud)

final InputStream in = FileInputStream("myfile");
try {
    ... use in ...
} finally {
    in.close();
}
Run Code Online (Sandbox Code Playgroud)

请注意,一般形式总是:

acquire;
try {
    use;
} finally {
    release;
}
Run Code Online (Sandbox Code Playgroud)

如果获取在try块内,则在采集失败的情况下将释放.在某些情况下,您可能会遇到不必要的代码(通常在上面的示例中测试null),但是在ReentrantLock的情况下,会发生坏事.

如果你经常做同样的事情,你可以使用"执行"这个习惯用法.不幸的是,Java的语法很冗长,所以有很多更大胆的板块.

fileInput("myfile", new FileInput<Void>() {
   public Void read(InputStream in) throws IOException {
       ... use in ...
       return null;
   }
});
Run Code Online (Sandbox Code Playgroud)

哪里

public static <T> T fileInput(FileInput<T> handler) throws IOException {
    final InputStream in = FileInputStream("myfile");
    try {
        handler.read(in);
    } finally {
        in.close();
    }
}
Run Code Online (Sandbox Code Playgroud)

更复杂的例子我,例如,换行异常.