@@ -22,11 +22,11 @@ public class ZipTest {
22
22
private static final String JPG_FILE_DIRECTORY = "D:\\ logs\\ test\\ photo\\ " ;
23
23
24
24
public static void main (String [] args ) {
25
- zipFileNoBuffer ();
25
+ /// zipFileNoBuffer();
26
26
///zipFileBuffer();
27
- //zipFileChannel();
27
+ /// zipFileChannel();
28
28
///zipFileMap();
29
- //zipFilePip();
29
+ /// zipFilePip();
30
30
}
31
31
32
32
/**
@@ -42,6 +42,7 @@ public static void zipFileNoBuffer() {
42
42
try (InputStream input = new FileInputStream (file )) {
43
43
zipOut .putNextEntry (new ZipEntry (file .getName ()));
44
44
int temp ;
45
+ // 调用本地方法与原生操作系统进行交互,从磁盘中读取数据。每读取一个字节的数据就调用一次本地方法与操作系统交互,是非常耗时的
45
46
while ((temp = input .read ()) != -1 ) {
46
47
zipOut .write (temp );
47
48
}
@@ -68,6 +69,8 @@ public static void zipFileBuffer() {
68
69
try (BufferedInputStream bufferedInputStream = new BufferedInputStream (new FileInputStream (file ))) {
69
70
zipOut .putNextEntry (new ZipEntry (file .getName ()));
70
71
int temp ;
72
+ // 如果使用缓冲区的话(这里假设初始的缓冲区大小足够放下30000字节的数据)那么只需要调用一次就行。
73
+ // 因为缓冲区在第一次调用read()方法的时候会直接从磁盘中将数据直接读取到内存中。随后再一个字节一个字节的慢慢返回。
71
74
while ((temp = bufferedInputStream .read ()) != -1 ) {
72
75
bufferedOutputStream .write (temp );
73
76
}
@@ -103,8 +106,8 @@ public static void zipFileChannel() {
103
106
}
104
107
105
108
/**
106
- * 使用内存映射文件
107
- * Version 4 使用Map映射文件
109
+ * Version 4 使用Map内存映射文件
110
+ * 内存中开辟了一段直接缓冲区,与数据直接作交互
108
111
*/
109
112
public static void zipFileMap () {
110
113
// 开始时间
@@ -186,17 +189,15 @@ public static void runTask(Pipe pipe) {
186
189
}
187
190
188
191
/**
189
- * noBuffer,
190
- * buffer,
191
- * channel,fileSize:859M ,consume time:77366
192
- * map
193
- * pip
192
+ * noBuffer,fileSize:20M,consume time:93916
193
+ * buffer,fileSize:20M,consume time:4478
194
+ * channel,fileSize:20M ,consume time:2711
195
+ * map,fileSize:20M,consume time:2395
196
+ * pip,fileSize:20M,consume time:3312
194
197
*
195
198
* @param time 开始时间
196
199
*/
197
200
private static void printInfo (long time ) {
198
- // fileSize:20M
199
- // consume time:29599
200
201
long size = FileUtils .sizeOfDirectory (new File (JPG_FILE_DIRECTORY ));
201
202
System .out .println ("fileSize:" + (size / 1024 / 1024 ) + "M" );
202
203
System .out .println ("consume time:" + (System .currentTimeMillis () - time ));
0 commit comments