很实用的功能,JAVA对文件进行操作,压缩和解压缩

1.对文件进行压缩

String[] filenames =new String[]{"c:\\qqq.txt","c:\\www.txt"}; 

 //new String[]{"c:\\aaa.txt", "c:\\bbb.java"}; 


 byte[] buf = new byte[1024]; 


 try { 

 String outFilename = "c:\\XXX.zip"; 

 ZipOutputStream out = 

 new ZipOutputStream(new FileOutputStream(outFilename)); 


 for (int i=0; i<filenames.length; i++) { 

 FileInputStream in = new FileInputStream(filenames[i]); 


 out.putNextEntry(new ZipEntry(filenames[i])); 


 int len; 

 while ((len = in.read(buf)) > 0) { 

 out.write(buf, 0, len); 

 } 


 out.closeEntry(); 

 in.close(); 

 } 


 out.close(); 

 } catch (IOException e) { 

 }


2.下面介绍如何解压缩

try { 

 String inFilename = "c:\\XXX.zip"); 

 ZipInputStream in = 

 new ZipInputStream(new FileInputStream(inFilename)); 



 ZipFile zf = new ZipFile("c:\\XXX.zip"); 


 for (Enumeration entries = 

 zf.entries(); entries.hasMoreElements();) 

 { 

 String zipEntryName = 

 ((ZipEntry)entries.nextElement()).getName(); 


 ZipEntry entry = in.getNextEntry(); 



 String outFilename = zipEntryName; 

 OutputStream out = new FileOutputStream(outFilename); 


 byte[] buf = new byte[1024]; 

 int len; 

 while ((len = in.read(buf)) > 0) { 

 out.write(buf, 0, len); 

 } 


 // Close the streams 

 out.close(); 

 } 



 in.close(); 

 } catch (IOException e) { 

 }