将多个文件压缩成zip(zip文件操作大全)

 String[] fileNames = {"11.txt","22.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(); 

 

你可能感兴趣的:(OS)