从接触计算机开始,便知道了压缩文件的存在,刚开始不解(本来我一次就可以打开文件,现在却多了一步,乃是解压。。。)到了后来,我才慢慢明白压缩的重要性,除了节省空间,还节省了时间。有时候压缩文件的结果会让你吃惊,大概在原文件的50%左右,这样在网络端传输的时间将缩短一半。由此可见,它是有多么的重要。
单个文件压缩
首选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输出流,只能使用字节流
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 {
//用校验流确保输出数据的完整性
CheckedOutputStream cos = new CheckedOutputStream(new FileOutputStream(outFile), new Adler32());
//用缓冲字节输出流进行包装
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);
}
}
}