java.util.zip

主要是三个类:
        ZipOutputStream         压缩文件使用
          ZipInputStream          解压缩文件使用
          ZipFile                循环压缩文件使用,也可以获得文件的数目
                   
1.将多个文件压缩到成一个文件夹
        String[] fileNames = {"tt.txt","haha.txt"};
       ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("tomorrow.zip"));
       
       byte[] buff = new byte[1024];
       for(int i = 0;i < fileNames.length ; i++)
       {
           FileInputStream is = new FileInputStream(fileNames[i]);
           
           zos.putNextEntry(new ZipEntry(fileNames[i]));        //最关键的是这一步
           int len = 0;
           while ((len = is.read(buff)) > 0 )
           {
               zos.write(buff, 0, len);
           }
           
           zos.closeEntry();        //需要注意的是这个地方
           is.close();
       }
       zos.close();

   2.罗列某个压缩文件中所有的文件名称
         ZipFile zf  = new ZipFile(new File("tomorrow.zip"));
        for(Enumeration<ZipEntry> entrys = (Enumeration<ZipEntry>)zf.entries() ; entrys.hasMoreElements();)
        {
            String zipEnteyName = entrys.nextElement().getName();
            System.out.println(zipEnteyName);
        }

   3. 解压缩ZIP文件
   //获得输入流
        ZipInputStream ziStream = new ZipInputStream(new FileInputStream("tomorrow.zip"));
        //主要是为了循环使用
        ZipFile zFile = new ZipFile(new File("tomorrow.zip"));
        
        for (Enumeration<ZipEntry> entries = (Enumeration<ZipEntry>)zFile.entries();entries.hasMoreElements();)
        {
            ZipEntry entry = ziStream.getNextEntry();
            if ( null == entry)
            {
                break;
            }
            String name = entry.getName();
            System.out.println(name);
            FileOutputStream os = new FileOutputStream(name);
            int len = 0;
            byte[] buff = new byte[1024];
            while ((len = ziStream.read(buff)) > 0)
            {
                os.write(buff, 0, len);
            }
            ziStream.closeEntry();
            os.close();
        }
        
        ziStream.close(); 
           

你可能感兴趣的:(java,OS)