服务端
/**
* nio将文件流写入response
* @author: zhanghp2017he@foxmail.com
* @date: 2022/8/22
* @param: [response]
* @return: void
* @exception:
*/
@RequestMapping("/download")
public void download(HttpServletResponse response) throws IOException {
OutputStream os = null;
try {
File file = new File("D:\\bao\\14个g.zip");
// 取得输出流
os = response.getOutputStream();
String contentType = Files.probeContentType(Paths.get(file.getAbsolutePath()));
response.setHeader("Content-Type", contentType);
response.setHeader("Content-Disposition", "attachment;filename="+ new String(file.getName().getBytes("utf-8"),"ISO8859-1"));
FileInputStream fileInputStream = new FileInputStream(file);
WritableByteChannel writableByteChannel = Channels.newChannel(os);
FileChannel fileChannel = fileInputStream.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024 * 20);
while (true) {
buffer.clear();
int flag = fileChannel.read(buffer);
if (flag == -1) {
break;
}
buffer.flip();
writableByteChannel.write(buffer);
}
fileChannel.close();
os.flush();
writableByteChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
//文件的关闭放在finally中
finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端
/**
* 从网页url下载大文件
* @author: zhanghp2017he@foxmail.com
* @date: 2022/8/22
* @param: [urlStr, file]
* @return: void
* @exception:
*/
public static void downloadWithNIO(String urlStr, String file) throws IOException {
URL url = new URL(urlStr);
ReadableByteChannel rbc = Channels.newChannel(url.openStream());
FileOutputStream fos = new FileOutputStream(file);
// fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
BufferedOutputStream buffOS = new BufferedOutputStream(fos);
ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024 * 20);
while (true) {
buffer.clear();
int flag = rbc.read(buffer);
if (flag == -1) {
break;
}
buffer.flip();
FileChannel fcout = fos.getChannel();
fcout.write(buffer);
}
buffOS.flush();
buffOS.close();
fos.flush();
fos.close();
rbc.close();
}