关于java的打包,解包编程

在百度上搜了半天也没有找到一个合适的,有的不能操作文件夹,有的不能操作单个文件,有的不支持中文,总之没有找到合适的(也可能是自己搜索的能力差一些),只好自己写一个,主要代码如下:

 

public static void unZip(File zipFileName, File outputDirectory)
   throws IOException {
  File rootDir = outputDirectory;
  rootDir.mkdirs();

  ZipInputStream in = null;
  try {
   in = new ZipInputStream(new FileInputStream(zipFileName));
   ZipEntry entry = in.getNextEntry();
   while (entry != null) {
    FileOutputStream out = null;
    try {
     if (!entry.isDirectory()) {
      File newFile = new File(rootDir, entry.getName());
      newFile.getParentFile().mkdirs();
      out = new FileOutputStream(newFile);
      copy(in, out);
     }
     entry = in.getNextEntry();
    } catch (IOException io) {
     io.printStackTrace();
     throw io;
    } finally {
     out.close();
    }
   }
  } finally {
   in.close();
  }

 }
打包的程序:

public static void zip(File zipFile, File inputFile) throws IOException {
  ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
  try {
   if (inputFile.isDirectory()) {
    File[] fl = inputFile.listFiles();
    for (int i = 0, length = fl.length; i < length; i++) {
     zip(out, fl[i], "");
    }
   } else {
    zip(out, inputFile, "");
   }
  } finally {
   out.close();
  }
 }

 public static void zip(ZipOutputStream out, File f, String base)
   throws IOException {
  // System.out.println("Zipping " + f.getName());
  if (AeUtil.notNullOrEmpty(base)) {
   base += "/";
  }
  String filePath = base + f.getName();
  if (f.isDirectory()) {

   File[] fl = f.listFiles();
   out.putNextEntry(new JarEntry(filePath + "/"));

   for (int i = 0, length = fl.length; i < length; i++) {
    zip(out, fl[i], filePath);
   }
  } else {
   out.putNextEntry(new JarEntry(filePath));
   FileInputStream in = new FileInputStream(f);
   try {
    copy(in, out);
   } catch (IOException io) {
    io.printStackTrace();
    throw io;
   } finally {
    in.close();
   }

  }
 }

public static long copy(InputStream aIn, OutputStream aOut, int aBufferSize)
   throws IOException {
  byte[] buffer = new byte[aBufferSize];
  int read = 0;
  long totalBytes = 0;
  while (-1 != (read = aIn.read(buffer))) {
   aOut.write(buffer, 0, read);
   totalBytes += read;
  }
  return totalBytes;
 }


 public static final int DEFAULT_BUFFER = 1024 * 4;

public static long copy(InputStream aIn, OutputStream aOut)
   throws IOException {
  return copy(aIn, aOut, DEFAULT_BUFFER);
 }
注意中文目录的问题,要加载apache的zip包,而不能是jdk自带的

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值