1

Possibly a duplicate, though I doubt so since I have not seen anything so far completely answering my criteria in a way that I can complete my program

Background

What I need is to access another jar, from a seperate jar, read and write files to that jar. So far what I have done is change the jar to a zip and then I can delete files, but the problem I am having is with writing files back in, specifically image files (.txt works perfectly fine)

Question

How do I write image files to a zip (that was originally a jar) from another java program (in the end product another jar)

Note

I have looked around and most sources say this is not possible, but those questions dealt with this during the running of a program, my special case is that the other program is not running, but in file format. All I want to do is write and image in and convert it back to a jar and not have any problems with running that jar in the end. Thank you!

  • you can unzip the files.write them and then zip them back – Muhammad Ali Nov 02 '19 at 02:35
  • @MuhammadAli Would writing the image in and then rezipping it cause any problems? Like is there any formatting issues that could occur? I don't know if java does and compression methods on its image files in the zip or anything like that. Also, thank you for your answer! – KrystosTheOverlord Nov 02 '19 at 02:49
  • 1
    Don’t write to a .jar file used at runtime. It will have unpredictable results. If you want to save data, save it to a known location and have your program look in that known location. – VGR Nov 02 '19 at 02:52
  • @VGR Nonono, I'm not writing while my jar is running, it is, let's just say program0 writes to program1, program1 is not running right now. It is not concurrent modification. – KrystosTheOverlord Nov 02 '19 at 02:58
  • That’s good. But it still sounds pretty unusual. Why write to a .jar file? Why not just save each image to a regular file? – VGR Nov 02 '19 at 03:00
  • 1
    I don't think there should be any issue in zipping files back. Java has a full native library that can zip files in a secure manner. See this answer https://stackoverflow.com/a/32962488/7392868 – Muhammad Ali Nov 02 '19 at 03:00
  • @VGR I was experimenting with a design that requires that when the new jars are made they are linked to a specific image, and when that jar is run, it runs with the image. I know that this is not the most optimal way, nor a very good way of doing it. This is simple for the idea that it is indeed possible that I'm pursuing the topic. – KrystosTheOverlord Nov 02 '19 at 03:16

1 Answers1

2

Use FileSystems to access, write and replace the contents of the jar file:

try (FileSystem fs = FileSystems.newFileSystem(Paths.get("path/file.jar"), null)) {
    Files.copy(Paths.get("path/to/image"), // path to an external image
               fs.getPath("image.jpg"),    // path inside a jar file
               StandardCopyOption.REPLACE_EXISTING);
}
Kirill Simonov
  • 8,257
  • 3
  • 18
  • 42