ossiejhmoore

How to add a file to an existing zip archive

Mar 29th, 2018
547
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.00 KB | None | 0 0
  1.         File zip = new File("/Users/ossiemoore/tmp/zipstuff/file.zip");
  2.         File addition = new File("/Users/ossiemoore/tmp/zipstuff/theme.xml");
  3.  
  4.         Map<String, String> env = new HashMap<>();
  5.         env.put("create", "true");
  6.         Path path = Paths.get(zip.getAbsolutePath());
  7.         String uriPath = "jar:" + path.toUri();
  8.         URI uri = URI.create(uriPath);
  9.         try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
  10.            
  11.             int size = (int)addition.length();
  12.             byte [] data = new byte[size];
  13.             InputStream is = new FileInputStream(addition);
  14.             is.read(data);
  15.            
  16.             Path themeDir = fs.getPath("theme");
  17.             Files.createDirectory(themeDir);
  18.            
  19.             Path nfInZip = fs.getPath("theme/theme1.xml");
  20.             try (Writer writer = Files.newBufferedWriter(nfInZip, StandardCharsets.UTF_8, StandardOpenOption.CREATE)) {
  21.                 writer.write(new String(data));
  22.             }
  23.         }
Advertisement
Add Comment
Please, Sign In to add comment