解决上传大文件时系统宕机问题

2017-02-20  本文已影响24人  梦沉薇露

一、错误示范

byte[] fileData = formFile.getFileData();   //获取上传文件的字节数据
if (fileData != null && fileData.length > 0) {
    FileOutputStream fos = new FileOutputStream(destFilePath);
    BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);
    bos.write(fileData);
    bos.flush();
    bos.close();
}

二、正确方式(注:饭要一口一口吃)

InputStream inputStream = formFile.getInputStream();
FileOutputStream fos = new FileOutputStream(destFilePath);
BufferedOutputStream bos = new BufferedOutputStream(fos, 1024);
int length = 0;
byte[] buffer = new byte[1024];
while ((length = inputStream.read(buffer)) != -1) {
    bos.write(buffer, 0, length);
}
bos.flush();
bos.close();
inputStream.close();
上一篇下一篇

猜你喜欢

热点阅读