java:java中的原生ZipOutputStream…,
分享于 点击 36496 次 点评:43
java:java中的原生ZipOutputStream…,
package com.xudeyu.stream;import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.util.Scanner; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream;
import javax.swing.JOptionPane;
public class ZipOutput {
public static void main(String[] args) throws IOException { ZipStream zip = new ZipStream(); // zip.zipFile("../data", "../data/zip.zip"); zip.zipDirectory("E:/CodeWriter/JavaCode/Data", "D:\\zip.zip"); }
}
class ZipStream {
public ZipStream() { }
public void zipFile(String originalZip, String targetZip) throws IOException { // 创建一个File类,方便读取 File originalFile = new File(originalZip);
// 创建一个目标zip文件 ZipOutputStream zout = new ZipOutputStream(new FileOutputStream( targetZip));
// 将原始文件的文件名作为一个条目 ZipEntry entry = new ZipEntry(originalFile.getName());
// 将一个条目添加到zip输出流 zout.putNextEntry(entry);
// 将原始文件写入zip流 BufferedInputStream in = new BufferedInputStream(new FileInputStream( originalFile));
int length = 0; while ((length = in.read()) != -1) { zout.write(length); }
// 关闭流 in.close(); zout.closeEntry(); zout.finish(); zout.close();
JOptionPane.showMessageDialog(null, "文件压缩完成!"); }
public void zipDirectory(String originalDir, String targetZip) throws IOException { // 创建一个文件输出流 ZipOutputStream zout = new ZipOutputStream(new FileOutputStream( targetZip));
File orifile = new File(originalDir);
// 采用递归遍历,添加每一个文件 zipEveryFile(targetZip, zout, orifile);
// 关闭流 zout.finish(); zout.close(); }
private void zipEveryFile(String targetZip, ZipOutputStream zout, File orifile) throws IOException, FileNotFoundException { // 如果待压缩的文件是目录,则遍历 if (orifile.isDirectory()) { File[] files = orifile.listFiles(); for (File afile : files) { // 压缩每一个出现的文件 zipEveryFile(targetZip, zout, new File(afile.getPath())); } }
// 如果是文件,则添加该项 if (orifile.isFile()) { // TODO;保存当前的目录名,再次遍历时把目录名加在ZipEntry的前面,这样就不用current time给添加标示了 ZipEntry entry = new ZipEntry(System.currentTimeMillis()+orifile.getName());
// 读取该文件所有的流 BufferedInputStream out = new BufferedInputStream( new FileInputStream(new File(orifile.getPath()))); // 添加一个条目 zout.putNextEntry(entry);
// 将文件信息添加入流 int length = 0; while ((length = out.read()) != -1) { // 写入文件流 zout.write(length); } // 单个文件关闭 out.close(); zout.closeEntry(); } } }
相关文章
- 暂无相关文章
用户点评