IO
java
@GetMapping("io")
public void downloadZip() {
long start = System.currentTimeMillis();
EntityWrapper<AttachmentEntity> wrapper = new EntityWrapper<>();
List<AttachmentEntity> attachments = attachmentMapper.selectList(wrapper);
String zpiName = "D:/data/压缩文件io.zip";
try (FileOutputStream fos = new FileOutputStream(
zpiName); ZipOutputStream zipOutputStream = new ZipOutputStream(fos)) {
int i = 0;
for (AttachmentEntity attachment : attachments) {
String uuid = UUID.randomUUID().toString();
FileInputStream fileInputStream = new FileInputStream(attachment.getPath());
zipOutputStream.putNextEntry(new ZipEntry(uuid + "/" + attachment.getName()));
IOUtils.copy(fileInputStream, zipOutputStream);
zipOutputStream.closeEntry();
fileInputStream.close();
i++;
}
} catch (IOException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start));
}
NIO
java
@GetMapping("nio")
public void downloadZipNio() throws FileNotFoundException {
long start = System.currentTimeMillis();
EntityWrapper<AttachmentEntity> wrapper = new EntityWrapper<>();
List<AttachmentEntity> attachments = attachmentMapper.selectList(wrapper);
String zpiName = "D:/data/压缩文件nio.zip";
try (FileOutputStream fos = new FileOutputStream(zpiName);
ZipOutputStream zos = new ZipOutputStream(fos);
WritableByteChannel wbc = Channels.newChannel(zos)) {
for (AttachmentEntity attachment : attachments) {
FileInputStream fis = new FileInputStream(attachment.getPath());
FileChannel channel = fis.getChannel();
String uuid = UUID.randomUUID().toString();
zos.putNextEntry(new ZipEntry(uuid + "/" + attachment.getName()));
channel.transferTo(0, channel.size(), wbc);
}
} catch (IOException e) {
e.printStackTrace();
}
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start));
}
运行时间对比(ms)
io | nio |
---|---|
375 | 349 |
350 | 321 |
340 | 330 |