1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
| import java.io.*; import java.util.zip.*; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream;
public class zipFile { List<String> fileList; zipFile(){ fileList = new ArrayList<String>(); }
public static void main( String[] args ) { zipFile appZip = new zipFile(); String SOURCE_FOLDER = args[0]; String OUTPUT_ZIP_FILE = args[1]; appZip.generateFileList(new File(SOURCE_FOLDER),SOURCE_FOLDER); appZip.zipIt(OUTPUT_ZIP_FILE,SOURCE_FOLDER); }
public void zipIt(String zipFile,String s_folder){
byte[] buffer = new byte[1024];
try{
FileOutputStream fos = new FileOutputStream(zipFile); ZipOutputStream zos = new ZipOutputStream(fos);
System.out.println("Output to Zip : " + zipFile);
for(String file : this.fileList){
System.out.println("File Added : " + file); ZipEntry ze= new ZipEntry(file); zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(s_folder + File.separator + file);
int len; while ((len = in.read(buffer)) > 0) { zos.write(buffer, 0, len); }
in.close(); }
zos.closeEntry(); zos.close();
System.out.println("Done"); }catch(IOException ex){ ex.printStackTrace(); } }
public void generateFileList(File node,String s_folder){
if(node.isFile()){ if (node.getAbsoluteFile().toString().toLowerCase().lastIndexOf(".txt") >0 ) { fileList.add(generateZipEntry(node.getAbsoluteFile().toString(),s_folder)); } }
if(node.isDirectory()){ String[] subNote = node.list(); for(String filename : subNote){ generateFileList(new File(node, filename),s_folder); } }
}
private String generateZipEntry(String file,String s_folder){ return file.substring(s_folder.length()+1, file.length()); } }
|