简介:ZIP文档(通常)以压缩格式存储了一个或多个文件,每个ZIP文档都有一个头,包含诸如每个文件名字和所使用的压缩方法等信息
注意:
- Exception in thread “main” java.lang.IllegalArgumentException: malformed input off : 0, length : 1
- windows环境下,默认字符集为GBK;ZipFile默认使用UTF-8字符集,当文件名存在中文时,处理时就会报错
new ZipInputStream(new FileInputStream(file), **Charset.**_**forName**_**("GBK")**);
ZipInputStream
public static void main(String[] args) {File file = new File("D:\\Charles\\Desktop\\房东的猫.zip");ZipInputStream zipInputStream = null;try {zipInputStream =new ZipInputStream(new FileInputStream(file), Charset.forName("GBK"));ZipEntry nextEntry;while ((nextEntry = zipInputStream.getNextEntry()) != null){System.out.println(nextEntry.getName());zipInputStream.closeEntry();}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}
getNextEntry()读取zip中的每一项,必须调用closeEntry()来读入下一项(不用也行)在读入单个ZIP项后,不要关闭ZIP输入流,也不要将其传递给可能会关闭它的方法。否则,你就不能再读入后续的项了
while ((zipEntry = zipInputStream.getNextEntry()) != null){Scanner scanner = new Scanner(zipInputStream);System.out.println(scanner.nextLine());zipInputStream.closeEntry();}
ZipOutputStream
创建 ZipOutputStream输出流
- 为每一项创建一个
new ZipEntry对象 zipOutputStream.putNextEntry(zip);zipOutputStream.write(scanner.nextLine().getBytes());**close.Entry();**~~~关闭这个ZIP文件中当前打开的项 ```java File file = new File(“D:\Charles\Desktop\demo.zip”); try {ZipInputStream zipInputStream =new ZipInputStream(new FileInputStream(file), Charset.forName("GBK"));ZipOutputStream zipOutputStream =new ZipOutputStream(new FileOutputStream("\\Charles\\Desktop\\test.zip"));ZipEntry zipEntry;while ((zipEntry = zipInputStream.getNextEntry()) != null){Scanner scanner = new Scanner(zipInputStream);ZipEntry zip = new ZipEntry("Java.txt");zipOutputStream.putNextEntry(zip);zipOutputStream.write(scanner.nextLine().getBytes());
zipInputStream.closeEntry();zipOutputStream.closeEntry();}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
``` JAR文件只是带有一个特殊项的ZIP文件,这个项称作清单。你可以使用JarInputStream和JarOutputStream类来读写清单项
ZipOutputStream
setLevel(int level)设置压缩级别,默认:Deflater.DEFAULT_COMPRESSION;级别设置无效则报异常- evel 压缩级别,从0(NO_COMPRESSION)到9(BEST_COMPRESSION)
setMethod(int method)设置压缩方法,这个压缩方法会作用于所有没有指定压缩方法的项上。- method 压缩方法:DEFLATED或STORED
ZipEntry
- long
getCrc()返回用于这个ZipEntry的CRC32校验和的值。 - long
getSize()返回这一项未压缩的尺寸,或者在未压缩的尺寸不可知的情况下返回-1 setMethod(int method)- method 用于这一项的压缩方法,必须是DEFLATED或STORED
setSize(long size)设置这一项的尺寸- 只有在压缩方法是STORED时才是必需的,size :这一项未压缩的尺寸
setCrc(long crc)给这一项设置CRC32校验和,这个校验和是使用CRC32类计算的。- 只有在压缩方法是STORED时才是必需的
ZipFile
ZipFile(String name |File file)用于从给定的字符串或File对象中读入数据Enumeration entries()返回一个Enumeration对象,枚举ZipFile中各个项的ZipEntry对象ZipEntry getEntry(String name)返回给定名字所对应的项,或者在没有对应项的时候返回null。- name 文件项名
InputStream getInputStream(ZipEntry ze)返回用于给定项的InputStream。- ze 这个ZIP文件中的一个ZipEntry
String getName()返回这个ZIP文件的路径。
