Watchful11

Untitled

May 28th, 2013
196
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. public static void zipFilesTo(File[] files, File outputLocation) {
  2. ZipOutputStream zipOutputStream = null;
  3. try {
  4. zipOutputStream = new ZipOutputStream(new FileOutputStream(outputLocation));
  5. addDirectoryOrFile(zipOutputStream, files, 0);
  6. } catch (Exception e) {
  7. e.printStackTrace();
  8. } finally {
  9. try {
  10. zipOutputStream.close();
  11. } catch (IOException e) { }
  12. }
  13. System.out.println("done");
  14. }
  15.  
  16. private static void addDirectoryOrFile(ZipOutputStream zipOutputStream, File[] files, int depth) throws IOException {
  17. for (int i=0; i<files.length; i++) {
  18. if (files[i].isDirectory()) {
  19. System.out.println("Adding directory " + files[i].getName());
  20. addDirectoryOrFile(zipOutputStream, files[i].listFiles(),depth+1);
  21. continue;
  22. }
  23.  
  24. byte[] buffer = new byte[1024];
  25.  
  26. String fileName = "";
  27. File temp = files[i];
  28. for(int j=0; j<depth; j++) {
  29. for(int k=depth-j; k>0; k--) {
  30. temp = temp.getParentFile();
  31. }
  32. fileName = fileName+temp.getName()+File.separator;
  33. temp = files[i];
  34. }
  35. fileName = fileName+files[i].getName();
  36. System.out.println("Adding file " + fileName);
  37.  
  38. FileInputStream fileInputStream = new FileInputStream(files[i]);
  39. zipOutputStream.putNextEntry(new ZipEntry(fileName));
  40.  
  41. int length = buffer.length;
  42. while ((length = fileInputStream.read(buffer)) > 0) {
  43. zipOutputStream.write(buffer, 0, length);
  44. }
  45.  
  46. zipOutputStream.closeEntry();
  47. fileInputStream.close();
  48. }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment