如何使用Java7 try with resources特性作为参数传递资源
我知道了。如果可关闭的资源作为参数出现,我们不需要声明资源。在这种情况下,我们如何使用此功能如何使用Java7 try with resources特性作为参数传递资源,java,try-catch,java-7,try-with-resources,Java,Try Catch,Java 7,Try With Resources,我知道了。如果可关闭的资源作为参数出现,我们不需要声明资源。在这种情况下,我们如何使用此功能 public static void write(byte[] b, OutputStream os) throws Exception { try { os.write(b); } catch(Exception e) { logger.log(Level.INFO, "Exception in writing byte array");
public static void write(byte[] b, OutputStream os) throws Exception {
try {
os.write(b);
}
catch(Exception e) {
logger.log(Level.INFO, "Exception in writing byte array");
}
finally {
try {
if(os != null) {
os.close();
}
}catch(Exception e) {
logger.log(Level.INFO, "Exception while close the outputstream");
throw e;
}
}
}
你可以简单地写:
static void write(byte[] b, OutputStream os) throws Exception {
try (OutputStream o = os) {
o.write(b);
}
}
一旦try块完成,它将调用方法
close
来关闭资源
try (BufferedWriter bw = new BufferedWriter(new FileWriter("file.out"))) {
bw.write("something");
}
资源应实现
Closable
接口旁注:关闭流通常是打开流的实体的责任。这看起来很奇怪,你正在接受一个开放的流,并在返回之前关闭它。(如果我想使用您的方法将内容写入文件,然后在内容后附加其他内容,该怎么办?),我确信我不会在之后追加内容。我将此代码作为实用方法编写。它是否是内部方法并不重要。不管怎样,这都是糟糕的设计。如果设计得当,很明显如何使用try with resources:您只需执行try(FileWriter fw=newfilewriter(“foo”){write(b,fw);}
。我同意@aioobe所说的,我刚才也指出,关闭其他人的流是问题的原因。如果必须在该方法中关闭流,我将调用方法writeAndCloseStream
,以明确该方法中的流发生了什么。如果我们这样做,资源“o”只会自动关闭,“os”资源保持打开?因为o=os
os是关闭的,因为它是相同的东西。