Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static void zipFilesTo(File[] files, File outputLocation) {
- ZipOutputStream zipOutputStream = null;
- try {
- zipOutputStream = new ZipOutputStream(new FileOutputStream(outputLocation));
- addDirectoryOrFile(zipOutputStream, files, 0);
- } catch (Exception e) {
- e.printStackTrace();
- } finally {
- try {
- zipOutputStream.close();
- } catch (IOException e) { }
- }
- System.out.println("done");
- }
- private static void addDirectoryOrFile(ZipOutputStream zipOutputStream, File[] files, int depth) throws IOException {
- for (int i=0; i<files.length; i++) {
- if (files[i].isDirectory()) {
- System.out.println("Adding directory " + files[i].getName());
- addDirectoryOrFile(zipOutputStream, files[i].listFiles(),depth+1);
- continue;
- }
- byte[] buffer = new byte[1024];
- String fileName = "";
- File temp = files[i];
- for(int j=0; j<depth; j++) {
- for(int k=depth-j; k>0; k--) {
- temp = temp.getParentFile();
- }
- fileName = fileName+temp.getName()+File.separator;
- temp = files[i];
- }
- fileName = fileName+files[i].getName();
- System.out.println("Adding file " + fileName);
- FileInputStream fileInputStream = new FileInputStream(files[i]);
- zipOutputStream.putNextEntry(new ZipEntry(fileName));
- int length = buffer.length;
- while ((length = fileInputStream.read(buffer)) > 0) {
- zipOutputStream.write(buffer, 0, length);
- }
- zipOutputStream.closeEntry();
- fileInputStream.close();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment