Last active
December 25, 2017 11:11
-
-
Save luanvuhlu/88bc8207065bb93d8cb98fdc8a9af8c2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AppZip | |
{ | |
List<String> fileList; | |
private static final String OUTPUT_ZIP_FILE = "C:\\MyFile.zip"; | |
private static final String SOURCE_FOLDER = "C:\\testzip"; | |
AppZip(){ | |
fileList = new ArrayList<String>(); | |
} | |
public static void main( String[] args ) | |
{ | |
AppZip appZip = new AppZip(); | |
appZip.generateFileList(new File(SOURCE_FOLDER)); | |
appZip.zipIt(OUTPUT_ZIP_FILE); | |
} | |
/** | |
* Zip it | |
* @param zipFile output ZIP file location | |
*/ | |
public void zipIt(String zipFile){ | |
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(SOURCE_FOLDER + File.separator + file); | |
int len; | |
while ((len = in.read(buffer)) > 0) { | |
zos.write(buffer, 0, len); | |
} | |
in.close(); | |
} | |
zos.closeEntry(); | |
//remember close it | |
zos.close(); | |
System.out.println("Done"); | |
}catch(IOException ex){ | |
ex.printStackTrace(); | |
} | |
} | |
/** | |
* Traverse a directory and get all files, | |
* and add the file into fileList | |
* @param node file or directory | |
*/ | |
public void generateFileList(File node){ | |
//add file only | |
if(node.isFile()){ | |
fileList.add(generateZipEntry(node.getAbsoluteFile().toString())); | |
} | |
if(node.isDirectory()){ | |
String[] subNote = node.list(); | |
for(String filename : subNote){ | |
generateFileList(new File(node, filename)); | |
} | |
} | |
} | |
/** | |
* Format the file path for zip | |
* @param file file path | |
* @return Formatted file path | |
*/ | |
private String generateZipEntry(String file){ | |
return file.substring(SOURCE_FOLDER.length()+1, file.length()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment