2011年11月29日 星期二

[ Java代碼範本 ] 用java壓縮/解壓縮文件示例(沒有中文問題)

參考 這裡 
這本是別人的東西,我只是修改了中文問題。在這個基礎上改一下就可以壓縮多個文件和目錄,甚至可以寫一個winzip之類的東東哦,有興趣的可以研究一下。 
壓縮Sample code:
  1. import java.io.*;  
  2. import java.util.zip.*;  
  3.   /** 
  4.    * @version Version 1.3 
  5.    */  
  6.   public class w0514{  
  7.        public static void main(String[] args){  
  8.           try{  
  9.               BufferedReader in=new BufferedReader(  
  10.                                   new InputStreamReader(new FileInputStream(args[0]),"ISO8859_1"));  
  11.               FileOutputStream f=new FileOutputStream(args[1]+".zip");  
  12.               CheckedOutputStream ch=new CheckedOutputStream(f,new CRC32());  
  13.               ZipOutputStream out=new ZipOutputStream(  
  14.                                      new BufferedOutputStream(ch));  
  15.          
  16.              int c;  
  17.              out.putNextEntry(new ZipEntry(args[0]));  
  18.              while((c=in.read())!=-1)  
  19.                  out.write(c);  
  20.                in.close();  
  21.                out.close();  
  22.              }  
  23.           catch(Exception e){  
  24.               e.printStackTrace();  
  25.              }  
  26.      }  
  27.   }  

解壓縮Sample code: 
Java內建支援ZIP格式檔案的壓縮及解壓縮,透過使用java.util.zip套件,我們可以用來將網頁上傳的ZIP檔案加以解壓縮再做後續處理。這裡我們可以先將解壓縮的固定步驟寫成一個UnZipBean,後續要解壓縮zip時只要先將檔名及解壓縮的目錄傳進去,再呼叫unzip()函式即可。 

詳細代碼請到 這裡 

下面是經過我改良過的Code: 
UnZipBean:
  1. package gays.util;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileOutputStream;  
  7. import java.io.FileNotFoundException;  
  8. import java.io.InputStream;  
  9. import java.io.IOException;  
  10. import java.util.Enumeration;  
  11. import java.util.zip.CRC32;  
  12. import java.util.zip.CheckedOutputStream;  
  13. import java.util.zip.ZipEntry;  
  14. import java.util.zip.ZipException;  
  15. import java.util.zip.ZipFile;  
  16. import java.util.zip.ZipOutputStream;  
  17. import java.io.*;  
  18.   
  19. public class UnZipBean {      
  20.     public static final int EOF = -1;  
  21.     static final int BUFFER = 2048;  
  22.   
  23.     private String zipFile;  
  24.     private String targetDirectory;  
  25.     private ZipFile zf;  
  26.       
  27.     /** Constructor */  
  28.     public UnZipBean() {         
  29.     }  
  30.       
  31.     public UnZipBean(String zipFile, String targetDirectory) {  
  32.         this.zipFile = zipFile;  
  33.         this.targetDirectory = targetDirectory;  
  34.     }  
  35.       
  36.     public void setZipFile(String zipFile) {  
  37.         this.zipFile = zipFile;  
  38.     }  
  39.       
  40.     public String getZipFile() {  
  41.         return zipFile;  
  42.     }  
  43.       
  44.     public void setTargetDirectory(String targetDirectory) {  
  45.         this.targetDirectory = targetDirectory;  
  46.     }  
  47.       
  48.     public String getTargetDirectory() {  
  49.         return targetDirectory;  
  50.     }  
  51.       
  52.     /** 
  53.      * BD : According to the input parameters, zip the file/folder indicated by member property:'s' and save 
  54.      *      into the file indicated by member property:'t'. If the  
  55.      * Change History : 
  56.      *   2009/09/27 John Lee 
  57.      *     Release 
  58.      * @param s 
  59.      * @param t 
  60.      * @return 
  61.      */  
  62.     public boolean zip(String s,String t){                
  63.         File source = new File(s);        
  64.         File target = new File(t);        
  65.         if(!target.exists()){  
  66.             try {  
  67.                 System.out.println("Prepare "+target.getAbsolutePath()+"...");  
  68.                 target.createNewFile();  
  69.             } catch (IOException e) {                 
  70.                 e.printStackTrace();  
  71.             }  
  72.         }  
  73.         if(source.exists()){  
  74.             try{                                  
  75.                 FileOutputStream f=new FileOutputStream(t);  
  76.                 CheckedOutputStream ch=new CheckedOutputStream(f,new CRC32());  
  77.                 ZipOutputStream out=new ZipOutputStream(  
  78.                          new BufferedOutputStream(ch));  
  79.                 zipFile(out,source);  
  80.                 out.closeEntry();  
  81.                 out.close();  
  82.                 return true;  
  83.             }catch(IOException ioe){  
  84.                 ioe.printStackTrace();  
  85.             }             
  86.         }else{  
  87.             System.err.println("Source File doesn't exist! "+source.getAbsolutePath());  
  88.         }  
  89.         return false;  
  90.     }  
  91.       
  92.     protected boolean zipFile(ZipOutputStream out,File f) throws IOException{         
  93.         if(f.exists()){           
  94.             if (f.isDirectory()) {  
  95.                 System.out.print("zipFile: "+f.getAbsolutePath());  
  96.                 File[] files = f.listFiles();  
  97.                 if(files.length==0){  
  98.                     System.out.println("(Empty folder)");  
  99.                     out.putNextEntry(new ZipEntry(f.getAbsoluteFile()+"/"));  
  100.                 }else{  
  101.                     System.out.println("("+files.length+")");  
  102.                 }  
  103.                 for(int i=0;i
  104.                   zipFile(out,files[i]);      
  105.                 }  
  106.             } else {  
  107.                 System.out.println("\tZIP "+f.getAbsolutePath()+"...");  
  108.                 out.putNextEntry(new ZipEntry(f.getAbsolutePath()));  
  109.                 byte[] buf = new byte[1024];  
  110.                 int len;  
  111.                 FileInputStream fis = new FileInputStream(f);  
  112.                 while ((len = fis.read(buf)) > 0) {  
  113.                     out.write(buf, 0, len);  
  114.                 }  
  115.                 fis.close();  
  116.             }         
  117.             return true;  
  118.         }else{  
  119.             System.out.println(f.getAbsolutePath()+" not exist!");  
  120.         }  
  121.         return false;  
  122.     }  
  123.       
  124.     /** 
  125.      * BD : Unzip the file indicated by member property:'zipFile' to the folder indicated by 
  126.      *      member property:'targetDirectory' 
  127.      * Change History : 
  128.      *   2009/09/27 John Lee 
  129.      *     Release 
  130.      * @return 
  131.      */  
  132.     public boolean unzip() {  
  133.         boolean done = false;  
  134.         if (zipFile != null) {            
  135.             try {              
  136.                 zf = new ZipFile(zipFile);  
  137.                 Enumeration enumeration = zf.entries();  
  138.                 while (enumeration.hasMoreElements()) {  
  139.                     ZipEntry target = (ZipEntry)enumeration.nextElement();  
  140.                     System.out.print(target.getName() + " .");  
  141.                     saveEntry(target);  
  142.                     System.out.println(". unpacked");  
  143.                 }  
  144.                 done = true;  
  145.             }  
  146.             catch (FileNotFoundException e){  
  147.                 System.out.println("zipfile not found"+e.getMessage());  
  148.             }  
  149.             catch (ZipException e){  
  150.                 System.out.println("zip error..."+e.getMessage());  
  151.             }  
  152.             catch (IOException e){  
  153.                 System.out.println("IO error..."+e.getMessage());  
  154.             }   
  155.             finally {  
  156.                 try {  
  157.                     zf.close();  
  158.                 } catch (IOException e) {  
  159.                     System.out.println("IO error...Can't close zip file"+e.getMessage());  
  160.                 }  
  161.             }  
  162.         }  
  163.         return done;  
  164.     }  
  165.   
  166.     private void saveEntry(ZipEntry target)  
  167.                                    throws ZipException, IOException {  
  168.         try {  
  169.             File file = new File(targetDirectory + File.separator + target.getName());  
  170.             if (target.isDirectory()) {  
  171.                 file.mkdirs();  
  172.             }  
  173.             else {  
  174.                 InputStream is = zf.getInputStream(target);  
  175.                 BufferedInputStream bis = new BufferedInputStream(is);  
  176.                 File dir = new File(file.getParent());  
  177.                 dir.mkdirs();  
  178.                 FileOutputStream fos = new FileOutputStream(file);  
  179.                 BufferedOutputStream bos = new BufferedOutputStream(fos);  
  180.   
  181.                 int c;  
  182.                 byte[] data = new byte[BUFFER];  
  183.                 while((c = bis.read(data, 0, BUFFER)) != EOF) {  
  184.                     bos.write(data, 0, c);  
  185.                 }  
  186.                 bos.flush();  
  187.                 bos.close();  
  188.                 fos.close();  
  189.             }  
  190.         }  
  191.         catch (ZipException e) {  
  192.             throw e;  
  193.         }  
  194.         catch (IOException e) {  
  195.             throw e;  
  196.         }  
  197.     }  
  198. }  

參考資料: 
http://java.sun.com/developer/technicalArticles/Programming/compression/ 
http://www.wakhok.ac.jp/~tatsuo/sen97/10shuu/UnZip.java.html 

1 則留言:

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...