.NET項目JAVA重構之壓縮&解壓縮

第一部分:
JAVA字符串壓縮和解壓縮實現

/*
字符串壓縮
*/
public static String Compress(String input) throws IOException {   
    if (input == null || input.length() == 0) {   
    return input;   
    }   
    ByteArrayOutputStream out = new ByteArrayOutputStream();   
    GZIPOutputStream gzip = new GZIPOutputStream(out);   
    gzip.write(input.getBytes());
    gzip.close();   
    return out.toString("ISO-8859-1"); 
    }  


/*
字符串解壓
*/
public static String Decompress(String input) throws IOException {   
    if (input == null || input.length() == 0) {   
    return input;   
    }   
    ByteArrayOutputStream out = new ByteArrayOutputStream();   
    ByteArrayInputStream in = new ByteArrayInputStream(
    input.getBytes("ISO-8859-1")); 
    GZIPInputStream gunzip = new GZIPInputStream(in);   
    byte[] buffer = new byte[256];   
    int n;   
    while ((n = gunzip.read(buffer))>= 0) {   
    out.write(buffer, 0, n);   
    }   
    // toString()使用平臺默認編碼,也可以顯式的指定如toString("GBK")   
    return out.toString();   
    }   

第二部分:
字節數組壓縮&解壓縮

/*
byte數組GZip壓縮
*/
public static byte[] Compress(byte[] data) {  
         byte[] res = null;  
         try {  
         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
         GZIPOutputStream gzip = new GZIPOutputStream(baos);  
         gzip.write(data);  
         gzip.finish();  
         gzip.close();  
         res = bos.toByteArray();  
         bos.close();  
         } catch (Exception ex) {  
         ex.printStackTrace();  
         }  
         return res;  
         }  



/*
byte數組GZip解壓縮
*/
public static byte[] Decompress(byte[] data) {  
        byte[] res = null;  
        try {  
        ByteArrayInputStream bais = new ByteArrayInputStream(data);  
        GZIPInputStream gzip = new GZIPInputStream(bais);  
        byte[] buf = new byte[1024];  
        int num = -1;  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        while ((num = gzip.read(buf, 0, buf.length)) != -1) {  
        baos.write(buf, 0, num);  
        }  
        res = baos.toByteArray();  
        baos.flush();  
        baos.close();  
        gzip.close();  
        bais.close();  
        } catch (Exception ex) {  
        ex.printStackTrace();  
        }  
        return res;  
        }  

注:以上爲實現代碼,具體的類和相關原理,有機會詳解。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章