java gzip 多个文件_Java Zip多文件压缩和 GZIP压缩
/**
* 多文件壓縮
*
* @author Administrator
*
*/
public class ZipCompress {
public static void main(String args[]) {
String[] filepaths = { "D:\\zip1.txt", "D:\\zip2.txt" };
try {
FileOutputStream f = new FileOutputStream("D://test.zip");
// 輸出校驗流,采用Adler32更快
CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
//創建壓縮輸出流
ZipOutputStream zos = new ZipOutputStream(csum);
BufferedOutputStream out = new BufferedOutputStream(zos);
//設置Zip文件注釋
zos.setComment("A test of java Zipping");
for (String s : filepaths) {
System.out.println("Writing file " + s);
//針對單個文件建立讀取流
BufferedReader bin = new BufferedReader(new FileReader(s));
//ZipEntry ZIP 文件條目
//putNextEntry 寫入新條目,并定位到新條目開始處
zos.putNextEntry(new ZipEntry(s));
int c;
while ((c = bin.read()) != -1) {
out.write(c);
}
bin.close();
out.flush();
}
out.close();
FileInputStream fi = new FileInputStream("D://test.zip");
CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32());
ZipInputStream in2 = new ZipInputStream(csumi);
BufferedInputStream bis = new BufferedInputStream(in2);
ZipEntry ze;
while ((ze = in2.getNextEntry()) != null) {
System.out.println("Reader File " + ze);
int x;
while ((x = bis.read()) != -1)
System.out.println(x);
}
//利用ZipFile解壓壓縮文件
ZipFile zf = new ZipFile("D:\\test.zip");
Enumeration e = zf.entries();
while(e.hasMoreElements()){
ZipEntry ze2 = (ZipEntry) e.nextElement();
System.out.println("File name : "+ze2);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 文件壓縮
* 把文件壓縮成GZIP 單一的流數據 并不是互異的數據
* GZIPOutputStream的使用
* @author Administrator
*
*/
public class GzipPcompress {
public static void main(String args[]) {
try {
BufferedReader in = new BufferedReader(new FileReader("D:\\gziptest.txt"));
BufferedOutputStream out = new BufferedOutputStream(
new GZIPOutputStream(new FileOutputStream("D:\\test.gz")));
System.out.println("Writing file");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
in.close();
out.close();
System.out.println("Reading file");
BufferedReader in2 = new BufferedReader(new InputStreamReader(
new GZIPInputStream(new FileInputStream("D:\\test.gz"))));
String s;
while((s=in2.readLine()) != null){
System.out.println(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
總結
以上是生活随笔為你收集整理的java gzip 多个文件_Java Zip多文件压缩和 GZIP压缩的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: asp.net记录错误日志的方法
- 下一篇: java如何让线程等待_如何使Java线