jdk1.7之后java不需要自己关闭io流了

以往,我们需要在finally中关闭自己写的io流,防止内存溢出,相当麻烦。如下

        InputStream is=null;
        InputStreamReader isr=null;
        BufferedReader read=null;
        try {
         is = new FileInputStream(new File(""));
         isr = new InputStreamReader(is);
         read = new BufferedReader(isr);
         String s = read.readLine();
        } finally {
             try {
                  if(null!=is){
                      is.close();
                  }
             }catch (Exception e){
                 e.printStackTrace();
             }
            try {
                if(null!=isr){
                    isr.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            try {
                if(null!=read){
                    read.close();
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

或者使用工具包,稍微简洁一些:

        InputStream is=null;
        InputStreamReader isr=null;
        BufferedReader read=null;
        try {
         is = new FileInputStream(new File(""));
         isr = new InputStreamReader(is);
         read = new BufferedReader(isr);
         String s = read.readLine();
        } finally {
            IOUtils.closeQuietly(read,isr,is);
        }

现在不需要手动关闭了,只要实现的自动关闭接口(Closeable)的类都可以在try结构体上定义,java会自动帮我们关闭,即使在发生异常的情况下也会。可以在try结构体上定义多个,用分号隔开即可

try (
    OutputStream out = new FileOutputStream("");
    OutputStream out2 = new FileOutputStream("")
){  
    // ...操作流代码  
} catch (Exception e) {  
    e.printStackTrace();
}  

 

你可能感兴趣的:(Java)