您的位置 首页 java

java 9 释放资源代码优化

jdk8之前释放资源代码

 import java.io.FileInputStream;
import java.io.IOException;
    //回顾jdk8之前释放资源的代码
public class JDK7 {
    
    public static void main(String[] args) {
    FileInputStream fileInputStream = null;
    try {
        
        //1. 建立程序与文件的数据通道
        fileInputStream = new FileInputStream("F:/a..txt");
        
        //2. 创建字节数组缓冲区
        byte[] buf = new byte[1024];
        int length = 0 ;
        
        //3. 读取数据,并且输出
        while((length = fileInputStream.read(buf))!=-1){
            
            System.out.println(new String(buf,0,length));
            
         }
        } catch (IOException e) {
             e.printStackTrace();
    } finally {
         fileInputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
     }
        
          }
        }
    }
}
  

通过上述代码我们可以看到释放资源代码非常累赘, 如果释放资源较多的时候,很容易就会出现释放资 源代码超过了正常业务的代码. 对此随着jdk版本的不断更新迭代,也对释放资源代码做了很大幅度的优化。

JDK8释放资源代码

 import java.io.FileInputStream;
import java.io.IOException;

//回顾jdk8之前释放资源的代码
public class JDK8 {
    public static void main(String[] args) {
        
    //需要释放资源的流,填写在try()中
    //注意:初始化流对象的代码一定要写在try()内部中。
    try( FileInputStream fileInputStream = new
        FileInputStream("F:/a.txt");){

        //1. 建立程序与文件的数据通道
        //2. 创建字节数组缓冲区
        byte[] buf = new byte[1024];
        int length = 0 ;

    //3. 读取数据,并且输出
    while((length = fileInputStream.read(buf))!=-1){
         System.out.println(new String(buf,0,length));
     }
    } catch (IOException e) {
        e.printStackTrace();
    }
 }
}
  

注意:JDK8开始已经不需要我们再手动关闭资源,只需要把要关闭资源的代码放入try语句中即可,但是要求初始化资源的语句必须位于try语句中

JDK9释放资源代码

 import java.io.FileNotFoundException;
import java.io.IOException;
 
public class JDK9 {
    public static void main(String[] args) throws FileNotFoundException {
    //需要释放资源的流,填写在try()中
    FileInputStream fileInputStream = new FileInputStream("F:/a.txt");
    try(fileInputStream){
        //1. 建立程序与文件的数据通道
        //2. 创建字节数组缓冲区
        byte[] buf = new byte[1024];
        int length = 0 ;
        //3. 读取数据,并且输出
        while((length = fileInputStream.read(buf))!=-1){
             System.out.println(new String(buf,0,length));
        }
    } catch (IOException e) {
        e.printStackTrace();
     }
    }
}  

小结

jdk9释放资源的语法格式如何?

try(流对象的变量|需要释放资源对象变量引用){

}catch(){

}

文章来源:智云一二三科技

文章标题:java 9 释放资源代码优化

文章地址:https://www.zhihuclub.com/169253.shtml

关于作者: 智云科技

热门文章

网站地图