压缩一个目录下的所有子文件夹,压缩一个目录文件夹,压缩一个目录下的所有子文
分享于 点击 44590 次 点评:216
压缩一个目录下的所有子文件夹,压缩一个目录文件夹,压缩一个目录下的所有子文
压缩一个目录下的所有子文件夹
[Java]代码
package test2;import java.io.*;import java.util.*;import java.util.zip.*;import java.nio.charset.*;public class TestZip { public static void main(String[] args) { String sourceDir="D:\\WebExpert"; int parentDirectoryLen=sourceDir.lastIndexOf(File.separator)+1; FileOutputStream fos = null; File zfile=new File("D:\\WebExpert.zip"); try { fos = new FileOutputStream(zfile); } catch (FileNotFoundException e1) { e1.printStackTrace(); zfile.delete(); return; } File[] copyfoldersList = new File(sourceDir).listFiles(); ZipOutputStream zipOut = new ZipOutputStream(fos,Charset.forName("GBK")); for (File myfile : copyfoldersList) { if (myfile.isDirectory()) { LinkedList<String> copysourcepath = new LinkedList<String>(Arrays.asList(myfile.getAbsolutePath())); while (copysourcepath.size() > 0) { File folders = new File(copysourcepath.peek()); String[] file = folders.list(); for (int i = 0; i < file.length; i++) { File ff = new File(copysourcepath.peek(), file[i]); if (ff.isFile()) { FileInputStream fis =null; try { fis = new FileInputStream(ff); ZipEntry entry = new ZipEntry(ff.getAbsoluteFile().toString().substring(parentDirectoryLen)); zipOut.putNextEntry(entry); int nNumber; byte[] buffer = new byte[Integer.MAX_VALUE/32]; while ((nNumber = fis.read(buffer)) != -1) zipOut.write(buffer, 0, nNumber); } catch (IOException e) { e.printStackTrace(); try { zipOut.close(); fos.close(); } catch (IOException e1) { e1.printStackTrace(); } return; }finally{ try { fis.close(); } catch (IOException e) {} } } else if (ff.isDirectory()) { for (File f : ff.listFiles()) { if (f.isDirectory()) copysourcepath.add(f.getPath()); else if (f.isFile()) { FileInputStream fis =null; try { fis = new FileInputStream(f); ZipEntry entry = new ZipEntry(f.getAbsoluteFile().toString().substring(parentDirectoryLen)); zipOut.putNextEntry(entry); int nNumber; byte[] buffer = new byte[Integer.MAX_VALUE/32]; while ((nNumber = fis.read(buffer)) != -1) zipOut.write(buffer, 0, nNumber); zipOut.flush(); } catch (IOException e) { e.printStackTrace(); try { zipOut.close(); fos.close(); } catch (IOException e1) { e1.printStackTrace(); } return; }finally{ try { fis.close(); } catch (IOException e) {} } } } } } copysourcepath.removeFirst(); } } } try { zipOut.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } }}
用户点评