- 論壇徽章:
- 0
|
/**
* 壓縮一個(gè)可序列化的對象
*
* @param object Object 原對象
* @return byte[] 對象經(jīng)壓縮后的字節(jié)流
* @throws IOException
*/
public static byte[] gZipEncode(Object object) throws IOException
{
//建立字節(jié)數(shù)組輸出流
ByteArrayOutputStream o = new ByteArrayOutputStream();
//建立gzip壓縮輸出流
GZIPOutputStream gzout = new GZIPOutputStream(o);
//建立對象序列化輸出流
ObjectOutputStream out = new ObjectOutputStream(gzout);
out.writeObject(object);
out.flush();
out.close();
gzout.close();
//返回壓縮字節(jié)流
byte[] data = o.toByteArray();
o.close();
return data;
}
/**
* 將字節(jié)流解壓縮并還原成一個(gè)對象
*
* @param data byte[] 字節(jié)流
* @return Object 還原出的對象
* @throws IOException
*/
public static Object gZipDecode(byte[] data) throws IOException
{
Object object = null;
//建立字節(jié)數(shù)組輸入流
ByteArrayInputStream i = new ByteArrayInputStream(data);
//建立gzip解壓輸入流
GZIPInputStream gzin = new GZIPInputStream(i);
//建立對象序列化輸入流
ObjectInputStream in = new ObjectInputStream(gzin);
//還原對象
try
{
object = in.readObject();
}
catch (ClassNotFoundException ex)
{
ex.printStackTrace();
}
i.close();
gzin.close();
in.close();
return object;
}
/**
* 將一個(gè)文件壓縮為GZIP格式
*
* @param inputFile File 源文件
* @param outputFile File 壓縮后的文件
* @throws IOException
*/
public static void gZipEncode(File inputFile, File outputFile) throws
IOException
{
//打開需壓縮文件作為文件輸入流
FileInputStream fin = new FileInputStream(inputFile);
//建立壓縮文件輸出流
FileOutputStream fout = new FileOutputStream(outputFile);
//建立gzip壓縮輸出流
GZIPOutputStream gzout = new GZIPOutputStream(fout);
byte[] buf = new byte[1024]; //設(shè)定讀入緩沖區(qū)尺寸
int num;
while ( (num = fin.read(buf)) != -1)
{
gzout.write(buf, 0, num);
}
gzout.close(); //關(guān)閉流,必須關(guān)閉所有輸入輸出流.保證輸入輸出完整和釋放系統(tǒng)資源.
fout.close();
fin.close();
}
/**
* 將一個(gè)GZIP格式的文件解壓
*
* @param inputFile File 壓縮文件
* @param outputFile File 解壓后的文件
* @throws IOException
*/
public static void gZipDecode(File inputFile, File outputFile) throws
IOException
{
//建立gzip壓縮文件輸入流
FileInputStream fin = new FileInputStream(inputFile);
//建立gzip解壓工作流
GZIPInputStream gzin = new GZIPInputStream(fin);
//建立解壓文件輸出流
FileOutputStream fout = new FileOutputStream(outputFile);
byte[] buf = new byte[1024];
int num;
while ( (num = gzin.read(buf, 0, buf.length)) != -1)
{
fout.write(buf, 0, num);
}
gzin.close();
fout.close();
fin.close();
}
直接采用了JAVA的壓縮包,另外的一種壓縮方法效率稍高,但解壓縮的時(shí)間比這個(gè)長,故采用這個(gè)。
本文來自ChinaUnix博客,如果查看原文請點(diǎn):http://blog.chinaunix.net/u/3516/showart_113163.html |
|