java压缩文件夹下的所有文件和选定文件

  昨天遇到压缩文件的问题,在网上找了好多相关的资料和例子,我最终找到一个比较好的例子,并做了一些小的修改。

  此例子可压缩一个文件夹中的所有文件,如下:

import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.tools.zip.ZipOutputStream; public class test { /** * * @param inputFileName 输入一个文件夹 * @param zipFileName 输出一个压缩文件夹,打包后文件名字 * @throws Exception */ public void zip(String inputFileName, String zipFileName) throws Exception { System.out.println(zipFileName); zip(zipFileName, new File(inputFileName)); } private void zip(String zipFileName, File inputFile) throws Exception { ZipOutputStream out = new ZipOutputStream(new FileOutputStream( zipFileName)); zip(out, inputFile, ""); System.out.println("zip done"); out.close(); } private void zip(ZipOutputStream out, File f, String base) throws Exception { if (f.isDirectory()) { //判断是否为目录 File[] fl = f.listFiles(); out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/")); base = base.length() == 0 ? "" : base + "/"; for (int i = 0; i < fl.length; i++) { zip(out, fl[i], base + fl[i].getName()); } } else { //压缩目录中的所有文件 out.putNextEntry(new org.apache.tools.zip.ZipEntry(base)); FileInputStream in = new FileInputStream(f); int b; System.out.println(base); while ((b = in.read()) != -1) { out.write(b); } in.close(); } } public static void main(String[] temp) { String inputFileName = "D://temp//test"; //你要压缩的文件夹 String zipFileName = "D://temp//test.zip"; //压缩后的zip文件 test book = new test(); try { book.zip(inputFileName, zipFileName); } catch (Exception ex) { ex.printStackTrace(); } } }   

 

org.apache.tools.zip.ZipOutputStream

其中这个包在ant.jar里

 

只要输入要压缩的文件夹和压缩后的文件名就OK了!

 

 

另外,此程序也可以改成压缩某几个文件,程序略加修改,传入要压缩的几个文件路径就可以了。如下:

private void zip(ZipOutputStream out, List listFile, String base) throws Exception { out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/")); base = base.length() == 0 ? "" : base + "/"; File filename = null; for (int i = 0; i < listFile.size(); i++) { filename = new File((String)listFile.get(i)); out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + filename.getName())); FileInputStream in = new FileInputStream(filename); int b; System.out.println(base); while ((b = in.read()) != -1) { out.write(b); } in.close(); } }

 

 

 补充一点,今天发现org.apache.tools.zip.ZipOutputStream包换成java.util.zip.ZipOutputStream也可以,那就用后者比较好了,不用再导入别的jar包了。

    但是有个问题,就是要压缩的文件如果文件名有中文的话使用java.util.zip.ZipOutputStream会产生乱码,而org.apache.tools.zip.ZipOutputStream就正常,这点一定要注意!!!

你可能感兴趣的:(java,exception,String,File,Class,import)