Java8 新的 try-with-resources 语句,自动资源释放

读取文件后需要释放资源,对于占用内存比较大的,非常重要;

(1)读取文件内存占用较多的优化方式: 一次读取部分处理完继续读取,可以有效的减少内存的占用;
使用RandomAccessFile可以从文件的任意位置读取,优势超级明显;
raf.seek(filePointer); 可以设置从文件的哪个指针位置读取,很方便高效;

(2)网络和带宽利用率不高的优化方式: 可以通过多线程发送请求更多的接口,或者增加每次接口请求的数据量,单个———>批量;


1. try-with-resources 读取完文件,自动资源释放


try (RandomAccessFile raf = new RandomAccessFile(filePath, "r");) {
          Image image = null;
	while((image = parseImage(raf)) != null){
              imageList.add(image);
          }
          return imageList;
 } catch(Exception e){
     log.error("parse file error, path: {},", path, e);
     return null;
 }

2. try catch finally 3件套,finnaly中关闭流


try {
    raf = new RandomAccessFile(filePath, "r");
    pgrLength = raf.length();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    // 关闭文件
    if (raf != null) {
        try {
            raf.close();
        } catch (IOException e) {
            log.error("file close error:", e);
            e.printStackTrace();
        }
    }
}

3. 读取文件时头上标识 注解

public static void customBufferStreamCopy(String[] args) throws Exception{
	@Cleanup InputStream in = new FileInputStream(args);
	@Cleanup OutputStream out = new FileOutputStream(args);
	byte[] buf = new byte[8192];  		   
    int i;  
    while ((i = in.read(buf)) != -1) {  
        out.write(buf, 0, i);  
    }  
}

参考:
https://www.oschina.net/question/12_10706

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序媛一枚~

您的鼓励是我创作的最大动力。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值