优化,解决(下载大文件时)内存一直往上涨,不释放的问题
// 链接url下载
private void downloadPicture(String urlList, String path) {
try {
URL url = new URL(urlList);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
ByteArrayOutputStream output = new ByteArrayOutputStream();
FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
//byte[] buffer = new byte[1024];
byte[] buffer = new byte[1024*1024];
int length;
int i = 0;//减少写入磁盘频率
while ((length = dataInputStream.read(buffer)) > 0) {
i++;
output.write(buffer, 0, length);
//like12 modified,20220125,优化,解决内存一直往上涨,不释放问题
fileOutputStream.write(output.toByteArray());//不再是全部读到内存后才写
if(i % 100 == 0){
fileOutputStream.flush();//立即写入磁盘
}
output.reset();//清零
}
//fileOutputStream.write(output.toByteArray());//放这里内存占用一直往上涨
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//下载
url = urlPreGlobalDoc + d.getEmployeeId() + "/" + d.getLocalPath();
path = pathPreGlobalDoc + d.getFilePath();
this.downloadPicture(url, path);
// 链接url下载图片
private void downloadPicture(String urlList, String path) {
try {
URL url = null;
url = new URL(urlList);
DataInputStream dataInputStream = new DataInputStream(url.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(
new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

374

被折叠的 条评论
为什么被折叠?



