经常会有文件过大,给文件的传输和增添了很多的麻烦,早先得知apach有个base64貌似可以用来压缩文件,但是测试没有什么效果,反而增大了文件的大小。今天了解了java自带的gzip包,如获至宝,超级好用又方便,记录下。
一、文件压缩
public static void compress(String fp_r,String fp_w){
try{
OutputStreamWriter os = new OutputStreamWriter(new GZIPOutputStream(new FileOutputStream(fp_w)),"utf-8");
PrintWriter pr = new PrintWriter(os);
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(new FileInputStream(fp_r), "utf-8"));
String line = null;
while((line = br.readLine())!=null){
pr.println(line);
}
pr.close();
br.close();
}catch(Exception e){
e.printStackTrace();
}
}
二、文件解压
public static void decompress(String fp_r,String fp_w){
try{
BufferedReader br = null;
InputStreamReader is = new InputStreamReader(new GZIPInputStream(new FileInputStream(new File(fp_r))),"utf-8");
br = new BufferedReader(is);
PrintWriter pr = new PrintWriter(new OutputStreamWriter(new FileOutputStream(fp_w),"utf-8"));
String line = null;
while((line = br.readLine())!=null){
pr.println(line);
}
br.close();
pr.close();
}catch(Exception e){
e.printStackTrace();
}
}