ossiejhmoore icon

How to add a file to an existing zip archive

ossiejhmoore | PRO | 03/29/18 01:58:19 PM UTC | 0 ⭐ | 532 👁️ | Never ⏰ | []
Java |

1 KB

|

None

|

0 👍

/

0 👎

        File zip = new File("/Users/ossiemoore/tmp/zipstuff/file.zip");
        File addition = new File("/Users/ossiemoore/tmp/zipstuff/theme.xml");
 
        Map<String, String> env = new HashMap<>();
        env.put("create", "true");
        Path path = Paths.get(zip.getAbsolutePath());
        String uriPath = "jar:" + path.toUri();
        URI uri = URI.create(uriPath);
        try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
            
            int size = (int)addition.length();
            byte [] data = new byte[size];
            InputStream is = new FileInputStream(addition);
            is.read(data);
            
            Path themeDir = fs.getPath("theme");
            Files.createDirectory(themeDir);
            
            Path nfInZip = fs.getPath("theme/theme1.xml");
            try (Writer writer = Files.newBufferedWriter(nfInZip, StandardCharsets.UTF_8, StandardOpenOption.CREATE)) {
                writer.write(new String(data));
            }
        }

Comments