批量文件壓縮爲ZIP

import java.io.*;
import java.util.*;
import java.util.zip.*;

public class ZipMaker {

 /**
  * @param args
  */

 public static void main(String[] args) {
  // TODO Auto-generated method stub
  
  File[] in;
  Scanner input=new Scanner(System.in);
  System.out.print("請輸入要生成壓縮文件的完整路徑:");
  String zippath=input.next();
  in = new File[args.length];
  for (int i = 0; i < args.length; i++) {
   try {
    in[i] = new File(args[i]);
    if (!in[i].exists())
     in[i].createNewFile();
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }

  try {
   File out = new File(zippath);
   if (!out.exists())
    out.createNewFile();
   FileOutputStream fout = new FileOutputStream(out);
   ZipOutputStream zout = new ZipOutputStream(
     new BufferedOutputStream(fout));
   for (int i = 0; i < args.length; i++) {
    System.out.println("writing file" + args[i]);
    BufferedInputStream bufin = new BufferedInputStream(
      new FileInputStream(in[i]));
    zout.putNextEntry(new ZipEntry(args[i]));
    int c;
    while ((c = bufin.read()) != -1) {
     zout.write(c);
    }
    bufin.close();
   }// for
   zout.close();

   System.out.println("reading file");
   FileInputStream fin = new FileInputStream(zippath);
   ZipInputStream zin = new ZipInputStream(
     new BufferedInputStream(fin));
   ZipEntry ze;
   while ((ze = zin.getNextEntry()) != null) {
    System.out.println("Reading file" + ze.getName());
    int x;
    while ((x = zin.read()) != -1)
     System.out.write(x);
    System.out.println();
   }
   zin.close();
  } catch (IOException e1) {
   e1.printStackTrace();
  }

 }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章