2015-10-14 82 views
3

我见过java7 try-with-resources。如果可关闭的资源是params,那么我们不需要声明资源。对于这种情况,我们该如何使用此功能?如何使用Java7试用资源功能作为参数传递资源

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; 
     } 
    } 
} 
+0

附注:关闭流通常是实体t的责任帽子打开了小溪。看起来很奇怪,你接受一个开放流并在你返回之前关闭它。 (如果我想用你的方法将东西写入文件,然后在你的内容之后添加其他内容?) – aioobe

+1

如果你真的想这样做,你可以简单地执行try(OutputStream os2 = os){ ...} – aioobe

+0

在我的情况下,我相信我不会追加内容后。我写这个代码作为一种实用方法。 – RJSV

回答

4

你可以简单的写:

static void write(byte[] b, OutputStream os) throws Exception { 
    try (OutputStream o = os) { 
     o.write(b); 
    } 
} 
+0

如果我们这样做,资源“o”只会自动关闭,“os”资源保持打开状态? – RJSV

+0

由于'o = os' os被关闭,因为它是一样的东西。 – Flown

0

一旦try块完成,它会调用该方法close关闭资源

try (BufferedWriter bw = new BufferedWriter(new FileWriter("file.out"))) { 
     bw.write("something"); 
    } 

资源应实现Closable接口