forked from kangjianwei/LearningJDK
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ZipFile.java
1957 lines (1657 loc) · 75.6 KB
/
ZipFile.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1995, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.util.zip;
import java.io.Closeable;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.io.UncheckedIOException;
import java.lang.ref.Cleaner.Cleanable;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.WeakHashMap;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.IntFunction;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import jdk.internal.misc.JavaLangAccess;
import jdk.internal.misc.JavaUtilZipFileAccess;
import jdk.internal.misc.SharedSecrets;
import jdk.internal.misc.VM;
import jdk.internal.perf.PerfCounter;
import jdk.internal.ref.CleanerFactory;
import jdk.internal.vm.annotation.Stable;
import static java.util.zip.ZipConstants64.EXTID_ZIP64;
import static java.util.zip.ZipConstants64.USE_UTF8;
import static java.util.zip.ZipConstants64.ZIP64_ENDHDR;
import static java.util.zip.ZipConstants64.ZIP64_ENDSIG;
import static java.util.zip.ZipConstants64.ZIP64_LOCHDR;
import static java.util.zip.ZipConstants64.ZIP64_LOCSIG;
import static java.util.zip.ZipConstants64.ZIP64_MAGICCOUNT;
import static java.util.zip.ZipConstants64.ZIP64_MAGICVAL;
import static java.util.zip.ZipUtils.CENCOM;
import static java.util.zip.ZipUtils.CENCRC;
import static java.util.zip.ZipUtils.CENEXT;
import static java.util.zip.ZipUtils.CENFLG;
import static java.util.zip.ZipUtils.CENHOW;
import static java.util.zip.ZipUtils.CENLEN;
import static java.util.zip.ZipUtils.CENNAM;
import static java.util.zip.ZipUtils.CENOFF;
import static java.util.zip.ZipUtils.CENSIG;
import static java.util.zip.ZipUtils.CENSIZ;
import static java.util.zip.ZipUtils.CENTIM;
import static java.util.zip.ZipUtils.ENDCOM;
import static java.util.zip.ZipUtils.ENDOFF;
import static java.util.zip.ZipUtils.ENDSIZ;
import static java.util.zip.ZipUtils.ENDTOT;
import static java.util.zip.ZipUtils.END_MAXLEN;
import static java.util.zip.ZipUtils.GETSIG;
import static java.util.zip.ZipUtils.LOCEXT;
import static java.util.zip.ZipUtils.LOCNAM;
import static java.util.zip.ZipUtils.LOCSIG;
import static java.util.zip.ZipUtils.READBLOCKSZ;
import static java.util.zip.ZipUtils.ZIP64_ENDOFF;
import static java.util.zip.ZipUtils.ZIP64_ENDSIZ;
import static java.util.zip.ZipUtils.ZIP64_ENDTOT;
import static java.util.zip.ZipUtils.ZIP64_LOCOFF;
import static java.util.zip.ZipUtils.get16;
import static java.util.zip.ZipUtils.get64;
/**
* This class is used to read entries from a zip file.
*
* <p> Unless otherwise noted, passing a {@code null} argument to a constructor
* or method in this class will cause a {@link NullPointerException} to be
* thrown.
*
* @author David Connelly
* @apiNote To release resources used by this {@code ZipFile}, the {@link #close()} method
* should be called explicitly or by try-with-resources. Subclasses are responsible
* for the cleanup of resources acquired by the subclass. Subclasses that override
* {@link #finalize()} in order to perform cleanup should be modified to use alternative
* cleanup mechanisms such as {@link java.lang.ref.Cleaner} and remove the overriding
* {@code finalize} method.
* @implSpec If this {@code ZipFile} has been subclassed and the {@code close} method has
* been overridden, the {@code close} method will be called by the finalization
* when {@code ZipFile} is unreachable. But the subclasses should not depend on
* this specific implementation; the finalization is not reliable and the
* {@code finalize} method is deprecated to be removed.
* @since 1.1
*/
/*
* zip文件,适用于读取具有完整zip结构的压缩文件
*
* 使用该类在解压zip文件时,需要借助zip文件的核心目录信息(zip文件的第二部分),
* 如果zip文件的结构是不完整的,如缺失了第二部分,那么该类无法正确识别zip实体信息。
*/
public class ZipFile implements ZipConstants, Closeable {
/**
* Mode flag to open a zip file for reading.
*/
public static final int OPEN_READ = 0x1; // 只读
/**
* Mode flag to open a zip file and mark it for deletion. The file will be
* deleted some time between the moment that it is opened and the moment
* that it is closed, but its contents will remain accessible via the
* {@code ZipFile} object until either the close method is invoked or the
* virtual machine exits.
*/
public static final int OPEN_DELETE = 0x4; // 删除,即解压后删除压缩包
private static final int STORED = ZipEntry.STORED;
private static final int DEFLATED = ZipEntry.DEFLATED;
private static final JavaLangAccess JLA;
private static boolean isWindows; // 当前是否处于windows系统
private final String name; // zip文件原始名称(路径)
@Stable
private final ZipCoder zc; // zip编/解码器
// The "resource" used by this zip file that needs to be
// cleaned after use.
// a) the input streams that need to be closed
// b) the list of cached Inflater objects
// c) the "native" source of this zip file.
@Stable
private final CleanableResource res; // 资源清理器
private volatile boolean closeRequested; // 当前zip文件是否已关闭
private String lastEntryName; // 最后访问的待压缩实体的名称(文件相对路径)
private int lastEntryPos; // 最后访问的的实体信息在核心目录表中的偏移量
static {
SharedSecrets.setJavaUtilZipFileAccess(new JavaUtilZipFileAccess() {
@Override
public boolean startsWithLocHeader(ZipFile zip) {
return zip.res.zsrc.startsWithLoc;
}
@Override
public String[] getMetaInfEntryNames(ZipFile zip) {
return zip.getMetaInfEntryNames();
}
@Override
public JarEntry getEntry(ZipFile zip, String name, Function<String, JarEntry> func) {
return (JarEntry) zip.getEntry(name, func);
}
@Override
public Enumeration<JarEntry> entries(ZipFile zip, Function<String, JarEntry> func) {
return zip.entries(func);
}
@Override
public Stream<JarEntry> stream(ZipFile zip, Function<String, JarEntry> func) {
return zip.stream(func);
}
@Override
public Stream<String> entryNameStream(ZipFile zip) {
return zip.entryNameStream();
}
});
JLA = jdk.internal.misc.SharedSecrets.getJavaLangAccess();
isWindows = VM.getSavedProperty("os.name").contains("Windows");
}
/*▼ 构造器 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Opens a zip file for reading.
*
* <p>First, if there is a security manager, its {@code checkRead}
* method is called with the {@code name} argument as its argument
* to ensure the read is allowed.
*
* <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
* decode the entry names and comments.
*
* @param name the name of the zip file
*
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
* @throws SecurityException if a security manager exists and its
* {@code checkRead} method doesn't allow read access to the file.
* @see SecurityManager#checkRead(java.lang.String)
*/
// 打开指定名称的ZipFile,使用UTF8编码作为解压字符集
public ZipFile(String name) throws IOException {
this(new File(name), OPEN_READ);
}
/**
* Opens a zip file for reading.
*
* <p>First, if there is a security manager, its {@code checkRead}
* method is called with the {@code name} argument as its argument
* to ensure the read is allowed.
*
* @param name the name of the zip file
* @param charset the {@linkplain java.nio.charset.Charset charset} to
* be used to decode the ZIP entry name and comment that are not
* encoded by using UTF-8 encoding (indicated by entry's general
* purpose flag).
*
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
* @throws SecurityException if a security manager exists and its {@code checkRead}
* method doesn't allow read access to the file
* @see SecurityManager#checkRead(java.lang.String)
* @since 1.7
*/
// 打开指定名称的ZipFile,使用charset作为解压字符集
public ZipFile(String name, Charset charset) throws IOException {
this(new File(name), OPEN_READ, charset);
}
/**
* Opens a ZIP file for reading given the specified File object.
*
* <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
* decode the entry names and comments.
*
* @param file the ZIP file to be opened for reading
*
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
*/
// 打开指定的ZipFile,使用UTF8编码作为解压字符集
public ZipFile(File file) throws ZipException, IOException {
this(file, OPEN_READ);
}
/**
* Opens a new {@code ZipFile} to read from the specified {@code File} object in the specified mode.
* The mode argument must be either {@code OPEN_READ} or {@code OPEN_READ | OPEN_DELETE}.
*
* <p>First, if there is a security manager, its {@code checkRead}
* method is called with the {@code name} argument as its argument to
* ensure the read is allowed.
*
* <p>The UTF-8 {@link java.nio.charset.Charset charset} is used to
* decode the entry names and comments
*
* @param file the ZIP file to be opened for reading
* @param mode the mode in which the file is to be opened
*
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
* @throws SecurityException if a security manager exists and
* its {@code checkRead} method
* doesn't allow read access to the file,
* or its {@code checkDelete} method doesn't allow deleting
* the file when the {@code OPEN_DELETE} flag is set.
* @throws IllegalArgumentException if the {@code mode} argument is invalid
* @see SecurityManager#checkRead(java.lang.String)
* @since 1.3
*/
/*
* 打开指定的ZipFile,使用UTF8编码作为解压字符集
* mode指示打开模式,一般为OPEN_READ或OPEN_READ|OPEN_DELETE
*/
public ZipFile(File file, int mode) throws IOException {
this(file, mode, StandardCharsets.UTF_8);
}
/**
* Opens a ZIP file for reading given the specified File object.
*
* @param file the ZIP file to be opened for reading
* @param charset The {@linkplain java.nio.charset.Charset charset} to be
* used to decode the ZIP entry name and comment (ignored if
* the <a href="package-summary.html#lang_encoding"> language
* encoding bit</a> of the ZIP entry's general purpose bit
* flag is set).
*
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
* @since 1.7
*/
// 打开指定的ZipFile,使用charset作为解压字符集
public ZipFile(File file, Charset charset) throws IOException {
this(file, OPEN_READ, charset);
}
/**
* Opens a new {@code ZipFile} to read from the specified {@code File} object in the specified mode.
* The mode argument must be either {@code OPEN_READ} or {@code OPEN_READ | OPEN_DELETE}.
*
* <p>First, if there is a security manager, its {@code checkRead}
* method is called with the {@code name} argument as its argument to
* ensure the read is allowed.
*
* @param file the ZIP file to be opened for reading
* @param mode the mode in which the file is to be opened
* @param charset the {@linkplain java.nio.charset.Charset charset} to
* be used to decode the ZIP entry name and comment that are not
* encoded by using UTF-8 encoding (indicated by entry's general
* purpose flag).
*
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
* @throws SecurityException if a security manager exists and its {@code checkRead}
* method doesn't allow read access to the file,or its
* {@code checkDelete} method doesn't allow deleting the
* file when the {@code OPEN_DELETE} flag is set
* @throws IllegalArgumentException if the {@code mode} argument is invalid
* @see SecurityManager#checkRead(java.lang.String)
* @since 1.7
*/
/*
* 打开指定的ZipFile,使用charset作为解压字符集
* mode指示打开模式,一般为OPEN_READ或OPEN_READ|OPEN_DELETE
*/
public ZipFile(File file, int mode, Charset charset) throws IOException {
if(((mode & OPEN_READ) == 0) || ((mode & ~(OPEN_READ | OPEN_DELETE)) != 0)) {
throw new IllegalArgumentException("Illegal mode: 0x" + Integer.toHexString(mode));
}
// 获取【文件/目录】的原始路径
String name = file.getPath();
SecurityManager sm = System.getSecurityManager();
if(sm != null) {
sm.checkRead(name);
if((mode & OPEN_DELETE) != 0) {
sm.checkDelete(name);
}
}
Objects.requireNonNull(charset, "charset");
this.zc = ZipCoder.get(charset);
this.name = name;
long t0 = System.nanoTime();
this.res = CleanableResource.get(this, file, mode);
PerfCounter.getZipFileOpenTime().addElapsedTimeFrom(t0);
PerfCounter.getZipFileCount().increment();
}
/*▲ 构造器 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ get ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns the path name of the ZIP file.
*
* @return the path name of the ZIP file
*/
// 返回(整个)zip文件原始名称(路径)
public String getName() {
return name;
}
/**
* Returns the zip file comment, or null if none.
*
* @return the comment string for the zip file, or null if none
*
* @throws IllegalStateException if the zip file has been closed
* @since 1.7
*/
// 返回(整个)zip文件的注释信息
public String getComment() {
synchronized(this) {
ensureOpen();
if(res.zsrc.comment == null) {
return null;
}
return zc.toString(res.zsrc.comment);
}
}
/**
* Returns the zip file entry for the specified name, or null
* if not found.
*
* @param name the name of the entry
*
* @return the zip file entry, or null if not found
*
* @throws IllegalStateException if the zip file has been closed
*/
// 返回zip文件中指定名称的实体信息
public ZipEntry getEntry(String name) {
return getEntry(name, ZipEntry::new);
}
/**
* Returns an input stream for reading the contents of the specified
* zip file entry.
* <p>
* Closing this ZIP file will, in turn, close all input streams that
* have been returned by invocations of this method.
*
* @param entry the zip file entry
*
* @return the input stream for reading the contents of the specified
* zip file entry.
*
* @throws ZipException if a ZIP format error has occurred
* @throws IOException if an I/O error has occurred
* @throws IllegalStateException if the zip file has been closed
*/
// 返回针对指定ZipEntry条目的(解压)输入流,可从中读取解压后的数据
public InputStream getInputStream(ZipEntry entry) throws IOException {
Objects.requireNonNull(entry, "entry");
int pos = -1; // 指定实体的偏移位置
Source zsrc = res.zsrc;
Set<InputStream> istreams = res.istreams;
synchronized(this) {
ensureOpen();
if(Objects.equals(lastEntryName, entry.name)) {
pos = lastEntryPos;
} else if(!zc.isUTF8() && (entry.flag & USE_UTF8) != 0) {
pos = zsrc.getEntryPos(zc.getBytesUTF8(entry.name), false);
} else {
pos = zsrc.getEntryPos(zc.getBytes(entry.name), false);
}
if(pos == -1) {
return null;
}
// 返回针对指定ZipEntry的输入流
ZipFileInputStream in = new ZipFileInputStream(zsrc.cen, pos);
// 判断该实体的压缩/解压方式
switch(CENHOW(zsrc.cen, pos)) {
case STORED:
synchronized(istreams) {
istreams.add(in);
}
// 对于未压缩的zip文件(没有本地文件头与数据描述符信息),直接返回输入流就可以读取
return in;
case DEFLATED:
/*
* Inflater likes a bit of slack
* MORE: Compute good size for inflater stream:
*/
long size = CENLEN(zsrc.cen, pos) + 2;
if(size>65536) {
size = 8192;
}
if(size<=0) {
size = 4096;
}
// 构造(解压)输入流
InputStream is = new ZipFileInflaterInputStream(in, res, (int) size);
synchronized(istreams) {
istreams.add(is);
}
// 对于压缩过的zip文件,需要返回对应的(解压)输入流才能对其解压
return is;
default:
throw new ZipException("invalid compression method");
}
}
}
/**
* Returns the number of entries in the ZIP file.
*
* @return the number of entries in the ZIP file
*
* @throws IllegalStateException if the zip file has been closed
*/
// 返回实体数目
public int size() {
synchronized(this) {
ensureOpen();
return res.zsrc.total;
}
}
/*▲ get ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ 序列 ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Returns an enumeration of the ZIP file entries.
*
* @return an enumeration of the ZIP file entries
*
* @throws IllegalStateException if the zip file has been closed
*/
// 返回一个ZipEntry实体迭代器
public Enumeration<? extends ZipEntry> entries() {
synchronized(this) {
ensureOpen();
return new ZipEntryIterator<ZipEntry>(res.zsrc.total, ZipEntry::new);
}
}
/**
* Returns an ordered {@code Stream} over the ZIP file entries.
*
* Entries appear in the {@code Stream} in the order they appear in
* the central directory of the ZIP file.
*
* @return an ordered {@code Stream} of entries in this ZIP file
*
* @throws IllegalStateException if the zip file has been closed
* @since 1.8
*/
// 返回ZipEntry实体流
public Stream<? extends ZipEntry> stream() {
synchronized(this) {
ensureOpen();
EntrySpliterator<ZipEntry> spliterator = new EntrySpliterator<>(0, res.zsrc.total, pos -> getZipEntry(null, null, pos, ZipEntry::new));
return StreamSupport.stream(spliterator, false);
}
}
/*▲ 序列 ████████████████████████████████████████████████████████████████████████████████┛ */
/*▼ ████████████████████████████████████████████████████████████████████████████████┓ */
/**
* Closes the ZIP file.
*
* <p> Closing this ZIP file will close all of the input streams
* previously returned by invocations of the {@link #getInputStream
* getInputStream} method.
*
* @throws IOException if an I/O error has occurred
*/
// 关闭zip文件
public void close() throws IOException {
if(closeRequested) {
return;
}
closeRequested = true;
synchronized(this) {
// Close streams, release their inflaters, release cached inflaters
// and release zip source
try {
res.clean();
} catch(UncheckedIOException ioe) {
throw ioe.getCause();
}
}
}
/**
* Ensures that the system resources held by this ZipFile object are
* released when there are no more references to it.
*
* @throws IOException if an I/O error has occurred
* @deprecated The {@code finalize} method has been deprecated and will be
* removed. It is implemented as a no-op. Subclasses that override
* {@code finalize} in order to perform cleanup should be modified to
* use alternative cleanup mechanisms and to remove the overriding
* {@code finalize} method. The recommended cleanup for ZipFile object
* is to explicitly invoke {@code close} method when it is no longer in
* use, or use try-with-resources. If the {@code close} is not invoked
* explicitly the resources held by this object will be released when
* the instance becomes unreachable.
*/
@Deprecated(since = "9", forRemoval = true)
protected void finalize() throws IOException {
}
/*▲ ████████████████████████████████████████████████████████████████████████████████┛ */
// 返回指定偏移处的实体的名称
private String getEntryName(int pos) {
byte[] cen = res.zsrc.cen;
int nlen = CENNAM(cen, pos);
if(!zc.isUTF8() && (CENFLG(cen, pos) & USE_UTF8) != 0) {
return zc.toStringUTF8(cen, pos + CENHDR, nlen);
} else {
return zc.toString(cen, pos + CENHDR, nlen);
}
}
/** Checks ensureOpen() before invoke this method */
// 返回指定偏移处名为name的实体条目
private ZipEntry getZipEntry(String name, byte[] bname, int pos, Function<String, ? extends ZipEntry> func) {
byte[] cen = res.zsrc.cen;
int nlen = CENNAM(cen, pos); // 实体名长度
int elen = CENEXT(cen, pos); // 扩展区长度
int clen = CENCOM(cen, pos); // 实体注释长度
int flag = CENFLG(cen, pos); // 通用位标记
if(name == null || bname.length != nlen) {
/*
* to use the entry name stored in cen, if the passed in name is
* (1) null, invoked from iterator, or
* (2) not equal to the name stored, a slash is appended during getEntryPos() search.
*/
if(!zc.isUTF8() && (flag & USE_UTF8) != 0) {
name = zc.toStringUTF8(cen, pos + CENHDR, nlen);
} else {
name = zc.toString(cen, pos + CENHDR, nlen);
}
}
// ZipEntry e = new ZipEntry(name);
ZipEntry e = func.apply(name);
e.flag = flag; // 通用位标记
e.xdostime = CENTIM(cen, pos); // 文件最后修改时间(日期)
e.crc = CENCRC(cen, pos); // crc-32校验码
e.size = CENLEN(cen, pos); // 压缩前的大小
e.csize = CENSIZ(cen, pos); // 压缩后的大小
e.method = CENHOW(cen, pos); // 压缩方法
if(elen != 0) {
int start = pos + CENHDR + nlen;
e.setExtra0(Arrays.copyOfRange(cen, start, start + elen), true);
}
if(clen != 0) {
int start = pos + CENHDR + nlen + elen;
if(!zc.isUTF8() && (flag & USE_UTF8) != 0) {
e.comment = zc.toStringUTF8(cen, start, clen);
} else {
e.comment = zc.toString(cen, start, clen);
}
}
lastEntryName = e.name;
lastEntryPos = pos;
return e;
}
/**
* Returns the zip file entry for the specified name, or null if not found.
*
* @param name the name of the entry
* @param func the function that creates the returned entry
*
* *@return the zip file entry, or null if not found
* @throws IllegalStateException if the zip file has been closed
*/
// 返回指定名称的ZipEntry实体信息
private ZipEntry getEntry(String name, Function<String, ? extends ZipEntry> func) {
Objects.requireNonNull(name, "name");
synchronized(this) {
ensureOpen();
// 编码:将字符串中的字符编码为字节后返回
byte[] bname = zc.getBytes(name);
// 返回拥有指定名称的实体信息在核心目录表中的偏移量
int pos = res.zsrc.getEntryPos(bname, true);
if(pos != -1) {
// 返回指定偏移处名为name的实体条目
return getZipEntry(name, bname, pos, func);
}
}
return null;
}
// 返回一个JarEntry实体迭代器
private Enumeration<JarEntry> entries(Function<String, JarEntry> func) {
synchronized(this) {
ensureOpen();
return new ZipEntryIterator<JarEntry>(res.zsrc.total, func);
}
}
/**
* Returns an ordered {@code Stream} over the zip file entries.
*
* Entries appear in the {@code Stream} in the order they appear in
* the central directory of the jar file.
*
* @param func the function that creates the returned entry
* @return an ordered {@code Stream} of entries in this zip file
* @throws IllegalStateException if the zip file has been closed
* @since 10
*/
// 返回JarEntry实体流
private Stream<JarEntry> stream(Function<String, JarEntry> func) {
synchronized(this) {
ensureOpen();
EntrySpliterator<JarEntry> spliterator = new EntrySpliterator<>(0, res.zsrc.total, pos -> (JarEntry) getZipEntry(null, null, pos, func));
return StreamSupport.stream(spliterator, false);
}
}
/**
* Returns an ordered {@code Stream} over the zip file entry names.
*
* Entry names appear in the {@code Stream} in the order they appear in
* the central directory of the ZIP file.
*
* @return an ordered {@code Stream} of entry names in this zip file
* @throws IllegalStateException if the zip file has been closed
* @since 10
*/
// 实体名称流
private Stream<String> entryNameStream() {
synchronized(this) {
ensureOpen();
EntrySpliterator<String> spliterator = new EntrySpliterator<>(0, res.zsrc.total, this::getEntryName);
return StreamSupport.stream(spliterator, false);
}
}
/**
* Returns the names of all non-directory entries that begin with
* "META-INF/" (case ignored). This method is used in JarFile, via
* SharedSecrets, as an optimization when looking up manifest and
* signature file entries. Returns null if no entries were found.
*/
// 返回元数据名称(路径)列表(即META-INF(子)目录内的文件名称)
private String[] getMetaInfEntryNames() {
synchronized(this) {
ensureOpen();
// zip文件的元数据
Source zsrc = res.zsrc;
if(zsrc.metanames == null) {
return null;
}
String[] names = new String[zsrc.metanames.length];
byte[] cen = zsrc.cen;
for(int i = 0; i<names.length; i++) {
int pos = zsrc.metanames[i];
names[i] = new String(cen, pos + CENHDR, CENNAM(cen, pos), StandardCharsets.UTF_8);
}
return names;
}
}
private void ensureOpen() {
if(closeRequested) {
throw new IllegalStateException("zip file closed");
}
if(res.zsrc == null) {
throw new IllegalStateException("The object is not initialized.");
}
}
private void ensureOpenOrZipException() throws IOException {
if(closeRequested) {
throw new ZipException("ZipFile closed");
}
}
// zip文件的元数据
private static class Source {
private static final int ZIP_ENDCHAIN = -1;
private static final int BUF_SIZE = 8192;
// zip文件
private RandomAccessFile zfile; // zfile of the underlying zip file
// zip文件及其基础文件属性的映射
private final Key key; // the key in files
// 缓存key和对应的Source
private static final HashMap<Key, Source> files = new HashMap<>();
// 记录缓存命中次数
private int refs = 1;
// (整个)zip文件的注释信息
private byte[] comment; // zip file comment
// 记录zip文件第二部分的全部内容和第三部分的起始标记
private byte[] cen; // CEN & ENDHDR
// 空隙
private long locpos; // position of first LOC header (usually 0)
// 实体数量
private int total; // total number of entries
// 元数据信息列表(即META-INF(子)目录内的文件实体对应的核心目录信息)
private int[] metanames; // list of meta entries in META-INF dir
/**
* A Hashmap for all entries.
* A cen entry of Zip/JAR file. As we have one for every entry in every active Zip/JAR,
* We might have a lot of these in a typical system. In order to save space we don't
* keep the name in memory, but merely remember a 32 bit {@code hash} value of the
* entry name and its offset {@code pos} in the central directory hdeader.
* private static class Entry {
* int hash; // 32 bit hashcode on name
* int next; // hash chain: index into entries
* int pos; // Offset of central directory file header
* }
* private Entry[] entries; // array of hashed cen entry
* To reduce the total size of entries further, we use a int[] here to store 3 "int"
* {@code hash}, {@code next and {@code "pos for each entry. The entry can then be
* referred by their index of their positions in the {@code entries}.
*/
// 实体信息列表
private int[] entries; // array of hashed cen entry
// 哈希表,记录实体信息位置
private int[] table; // Hash chain heads: indexes into entries
// 哈希表长度
private int tablelen; // number of hash heads
// 该zip文件是否以LOCSIG标记(属于zip文件的第一部分的第1小节)开头
private final boolean startsWithLoc; // true, if zip file starts with LOCSIG (usually true)
// 构造zip文件的元数据,toDelete指示zip解压后是否将原压缩包删除
private Source(Key key, boolean toDelete) throws IOException {
this.key = key;
// zip访问结束后需要将其删除
if(toDelete) {
// 在windows系统上,靠着O_TEMPORARY参数完成访问后删除这个动作
if(isWindows) {
this.zfile = SharedSecrets.getJavaIORandomAccessFileAccess().openAndDelete(key.file, "r");
// 非windows系统上,不支持O_TEMPORARY参数,所以在缓存中打开zip后,直接将其原文件删除
} else {
this.zfile = new RandomAccessFile(key.file, "r");
key.file.delete();
}
// 不删除原压缩包
} else {
this.zfile = new RandomAccessFile(key.file, "r");
}
try {
// 解析zip文件的元数据(读取核心目录区域(zip文件的第二部分))
initCEN(-1);
byte[] buf = new byte[4];
readFullyAt(buf, 0, 4, 0);
this.startsWithLoc = (LOCSIG(buf) == LOCSIG);
} catch(IOException x) {
try {
this.zfile.close();
} catch(IOException xx) {
}
throw x;
}
}
// 工厂方法,构造zip文件的元数据对象,toDelete指示zip解压后是否将原压缩包删除
static Source get(File file, boolean toDelete) throws IOException {
// 获取指定路径标识的文件的基础文件属性
BasicFileAttributes attrs = Files.readAttributes(file.toPath(), BasicFileAttributes.class);
Key key = new Key(file, attrs);
Source src;
synchronized(files) {
// 先尝试从缓存中获取src
src = files.get(key);
if(src != null) {
src.refs++; // 如果获取到了目标值,则引用计数增一
return src;
}
}
// 构造新的Source对象
src = new Source(key, toDelete);
synchronized(files) {
if(files.containsKey(key)) { // someone else put in first
src.close(); // close the newly created one
src = files.get(key);
src.refs++;
return src;
}
// 加入缓存
files.put(key, src);
return src;
}
}
/* Reads zip file central directory */
// 解析zip文件的元数据(读取核心目录区域(zip文件的第二部分))
private void initCEN(int knownTotal) throws IOException {
// 实体数量未知
if(knownTotal == -1) {
// 获取核心目录相关信息(zip文件第二部分)
End end = findEND();
if(end.endpos == 0) {
locpos = 0;
total = 0;
entries = new int[0];
cen = null;
return; // only END header present
}
if(end.cenlen>end.endpos) {
zerror("invalid END header (bad central directory size)");
}
// 核心目录表(zip文件第二部分)在zip文件中的起始位置
long cenpos = end.endpos - end.cenlen; // position of CEN table
/*
* Get position of first local file (LOC) header,
* taking into account that there may be a stub prefixed to the zip file.
*/
// 空隙
locpos = cenpos - end.cenoff;
if(locpos<0) {
zerror("invalid END header (bad central directory offset)");
}
// read in the CEN and END
cen = new byte[(int) (end.cenlen + ENDHDR)];
if(readFullyAt(cen, 0, cen.length, cenpos) != end.cenlen + ENDHDR) {
zerror("read CEN tables failed");
}
total = end.centot;
} else {