從接觸計(jì)算機(jī)開始绸吸,便知道了壓縮文件的存在鼻弧,剛開始不解(本來我一次就可以打開文件,現(xiàn)在卻多了一步锦茁,乃是解壓攘轩。。码俩。)到了后來度帮,我才慢慢明白壓縮的重要性,除了節(jié)省空間稿存,還節(jié)省了時(shí)間笨篷。有時(shí)候壓縮文件的結(jié)果會讓你吃驚,大概在原文件的50%左右瓣履,這樣在網(wǎng)絡(luò)端傳輸?shù)臅r(shí)間將縮短一半率翅。由此可見,它是有多么的重要袖迎。
單個(gè)文件壓縮
首選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 {
//用校驗(yàn)流確保輸出數(shù)據(jù)的完整性
CheckedOutputStream cos = new CheckedOutputStream(new FileOutputStream(outFile), new Adler32());
//用緩沖字節(jié)輸出流進(jìn)行包裝
zipStream = new ZipOutputStream(new BufferedOutputStream(cos));
for (File file : files) {
if(file != null) {
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
try {
//添加實(shí)體到流中,實(shí)際上只需要指定文件名稱
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);
}
}
}