笔记:I/O流-ZIP文档

ZIP文档以压缩格式存储了一个或多个文件,每个ZIP文档都有一个头,包含诸如每个文件名字和所使用的压缩方法等信息,在 Java 中可以使用 ZipInputStream 来读入ZIP 文档,getNextEntry 方法返回一个描述这些项的 ZipEntry 类型的对象,ZipInputStream read 方法被修改为在碰到当前项的结尾时返回 -1,然后必须调用 closeEntry 来读入下一个项,示例代码如下:

                ZipInputStream inputStream = null;

                try {

                        inputStream = new ZipInputStream(new FileInputStream("x64.zip"));

                        ZipEntry entry = null;

                        while ((entry = inputStream.getNextEntry()) != null) {

// 将每个项的内容单独保存为文件

                                saveFile(entry.getName(), inputStream);

                                inputStream.closeEntry();

                        }

                } catch (FileNotFoundException ex) {

                        ex.printStackTrace();

                } finally {

                        if (inputStream != null) {

                                inputStream.close();

                        }

                }

要写入到ZIP文件,可以使用ZipOutputStream类,对于希望放入到ZIP文件中的项,都应该创建一个ZipEntry对象,并将文件名称传递给ZipEntry构造函数,并设置默认的日期、解压缩参数等,然后调用 putNextEntry 方法增加项,并向流中写入内容,最后调用 closeEntry 来关闭项,示例代码如下:

           // 将多个文件增加到压缩文件中

                ZipOutputStream outputStream = null;

                String[] fileNames = new String[]{"PrintWriter.log", "filestream.dat",".idea\\compiler.xml"};

                try {

                        outputStream = new ZipOutputStream(new FileOutputStream("zipStreamApp.zip"));

                        for (String fileName : fileNames) {

                                ZipEntry entry = new ZipEntry(fileName);

                                outputStream.putNextEntry(entry);

                                byte[] fileBytes = readFile(fileName);

                                outputStream.write(fileBytes);

                                outputStream.closeEntry();

                        }

                }

                finally {

                        if(outputStream != null){

                                outputStream.close();

                        }

                }

   

   

posted @ 2017-05-03 22:13  立3807  阅读(169)  评论(0编辑  收藏  举报