• 笔记: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();

                            }

                    }

       

       

  • 相关阅读:
    0713学期末了
    Oracle Redo日志的状态
    crontab调用shell访问sqlplus失败原因
    Solaris下批量杀进程
    oracle用户管理的完全恢复4:在ARCHIVELOG 模式(恢复打开的数据库)
    oracle用户管理的完全恢复3:在ARCHIVELOG 模式(恢复关闭的数据库)
    shell删除所有空行(忽略编码格式)
    oracle用户管理的完全恢复1:在NOARCHIVELOG 模式下执行恢复
    查看oracle用户权限
    OLTP与OLAP介绍
  • 原文地址:https://www.cnblogs.com/li3807/p/6804284.html
Copyright © 2020-2023  润新知