從接觸計算機開始,便知道了壓縮文件的存在,剛開始不解(本來我一次就可以打開文件,現(xiàn)在卻多了一步,乃是解壓。。。)到了后來,我才慢慢明白壓縮的重要性,除了節(jié)省空間,還節(jié)省了時間。有時候壓縮文件的結(jié)果會讓你吃驚,大概在原文件的50%左右,這樣在網(wǎng)絡端傳輸?shù)臅r間將縮短一半。由此可見,它是有多么的重要。
單個文件壓縮
首選GZIP
public static void compress(File source, File gzip) {
if(source == null || gzip == null)
throw new NullPointerException();
BufferedReader reader = null;
BufferedOutputStream bos = null;
try {
//讀取文本文件可以字符流讀取
reader = new BufferedReader(new FileReader(source));
//對于GZIP輸出流,只能使用字節(jié)流
bos = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(gzip)));
String data;
while((data = reader.readLine()) != null) {
bos.write(data.getBytes());
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try {
if(reader != null)
reader.close();
if(bos != null)
bos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
多文件壓縮
public static void compressMore(File[] files, File outFile) {
if(files == null || outFile == null)
throw new NullPointerException();
ZipOutputStream zipStream = null;
try {
//用校驗流確保輸出數(shù)據(jù)的完整性
CheckedOutputStream cos = new CheckedOutputStream(new FileOutputStream(outFile), new Adler32());
//用緩沖字節(jié)輸出流進行包裝
zipStream = new ZipOutputStream(new BufferedOutputStream(cos));
for (File file : files) {
if(file != null) {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
try {
//添加實體到流中,實際上只需要指定文件名稱
zipStream.putNextEntry(new ZipEntry(file.getName()));
int c;
while((c = in.read()) != -1)
zipStream.write(c);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
in.close();
}
}
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
try{
if(zipStream != null)
zipStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}