Java8 新的 try-with-resources 语句,自动资源释放
生活随笔
收集整理的這篇文章主要介紹了
Java8 新的 try-with-resources 语句,自动资源释放
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
讀取文件后需要釋放資源,對(duì)于占用內(nèi)存比較大的,非常重要;
(1)讀取文件內(nèi)存占用較多的優(yōu)化方式: 一次讀取部分處理完繼續(xù)讀取,可以有效的減少內(nèi)存的占用;
使用RandomAccessFile可以從文件的任意位置讀取,優(yōu)勢(shì)超級(jí)明顯;
raf.seek(filePointer); 可以設(shè)置從文件的哪個(gè)指針位置讀取,很方便高效;
(2)網(wǎng)絡(luò)和帶寬利用率不高的優(yōu)化方式: 可以通過多線程發(fā)送請(qǐng)求更多的接口,或者增加每次接口請(qǐng)求的數(shù)據(jù)量,單個(gè)———>批量;
1. try-with-resources 讀取完文件,自動(dòng)資源釋放
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中關(guān)閉流
try {raf = new RandomAccessFile(filePath, "r");pgrLength = raf.length();
} catch (FileNotFoundException e) {e.printStackTrace();
} catch (IOException e) {e.printStackTrace();
} finally {// 關(guān)閉文件if (raf != null) {try {raf.close();} catch (IOException e) {log.error("file close error:", e);e.printStackTrace();}}
}
3. 讀取文件時(shí)頭上標(biāo)識(shí) 注解
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
總結(jié)
以上是生活随笔為你收集整理的Java8 新的 try-with-resources 语句,自动资源释放的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: SpringBoot配置postgre多
- 下一篇: 使用OpenCV,Python进行图像哈