0

I know that this question is a duplicate of : 1) Java - Writing to txt in a JAR file 2) How to read/write file in jar 3) How can modify/edit a file data which is inside a jar?

But I've read it all and I still not have a concrete answer.

If I have a .jar file with this tree:

(dir)META-INF -> MANIFEST.MF

(dir)test -> test.txt
          -> Test.class

I can read the .txt file with this code:

 public String readFromJARFile(String filename)throws IOException {
           InputStream is = getClass().getResourceAsStream(filename);
           InputStreamReader isr = new InputStreamReader(is);
           BufferedReader br = new BufferedReader(isr);
           StringBuffer sb = new StringBuffer();
           String line;
           while ((line = br.readLine()) != null) {
             sb.append(line);
           }
           br.close();
           isr.close();
           is.close();
           return sb.toString();
}

If I need to write into that .txt file, can I do it? If yes, how? If not, why?

Thanks.

Community
  • 1
  • 1
delvedor
  • 52
  • 1
  • 10
  • Most of the noted duplicates include a comment or answer along the lines of "don't do that!". Sounds like a good answer to me. – Don Roby Nov 28 '13 at 16:50
  • Without reading the other answers, I can tell you it's a terrible idea because a jar file is also a zip file. A zip file is not designed to be used as a dynamic filesystem. You probably could make it work (in some cases) with a [FUSE file system](http://code.google.com/p/fuse-zip/) on linux, but I wouldn't even try. It would be easier to store and access an externalized file (perhaps even generated from the contents of your JAR). – Elliott Frisch Nov 28 '13 at 16:53
  • I understand the part of _"don't do that!"_ , but if I do, what could happen? – delvedor Nov 28 '13 at 17:31
  • 1
    The only working way is to create another jar/zip file with the modified contents and replace the original file with the new one afterwards. This will be a heavy operation if you just want to modify a single entry inside a big jar. But that’s how, e.g. `jar uf …` works. – Holger Nov 28 '13 at 17:55

0 Answers0