0

I was trying to copy a file into a A.jar (without extracting it) but it didn't work. Suppose I have file "copy.txt" in "D:\java\copy.txt" and i want this file to be copied into my "A.jar/org/here" . if the file is already exist then it should replace it.

i tried modifying the below code but it didn't work.

import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class deploy {
public static void main(String[] argv) {
    Path myFilePath = Paths.get("C:/Users/ma329300/Desktop/copy.txt");

    Path zipFilePath = Paths.get("D:/java/A.jar");
    try( FileSystem fs = FileSystems.newFileSystem(zipFilePath, null) ){
        Path fileInsideZipPath = fs.getPath("/org/copy.txt");
        Files.copy(myFilePath, fileInsideZipPath);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}
  • Possible duplicate of [Java - Writing to txt in a JAR file](https://stackoverflow.com/questions/13937904/java-writing-to-txt-in-a-jar-file) – Arnaud Feb 05 '18 at 10:11
  • "Didn't work" is an extremely bad way to explain you problem. What exactly did not work and how? – M. Prokhorov Feb 05 '18 at 10:15
  • Means it is giving an err - Exception in thread "main" java.nio.file.FileSystemNotFoundException: D:\java\A.jar at com.sun.nio.zipfs.ZipFileSystem.(ZipFileSystem.java:110) at com.sun.nio.zipfs.ZipFileSystemProvider.newFileSystem(ZipFileSystemProvider.java:130) at java.nio.file.FileSystems.newFileSystem(Unknown Source) at com.mani.maximo.deploy.main(deploy.java:15) –  Feb 05 '18 at 10:22

1 Answers1

0

First of all, check your paths. Java is really tricky with the paths and should be in full path form. Try putting the backslashes like "D:\java\A.jar", as windows works differently than linux.

Also, if you change your file and re-compile, it will generate a new .jar each time, with the updated file you wanted to change. That would solve your problem without having to access your .jar externally.

I tried once to access libraries packed on a .jar and load them with the code inside the .jar too and didn't worked propperly, so be carefull.

Another thing you should be aware of is that you cannot modify a .jar directly without decompressing, as it uses a special algorythm in order to get the indexation properly done for and by java. Changing one specific part of the .jar could corrupt the data into it and make it crash on the run.

Hope it helped.