读取文件后需要释放资源,对于占用内存比较大的,非常重要;
(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);
}
}