0

After exhausting the internet looking for the proper way to write a stream of data within a running JAR file, I have no idea how to take a stream of data, (say a string) and output to a *.txt file next to the *.jar. Here's my writing attempt:

InputStream stream = new ByteArrayInputStream("some string".getBytes("UTF-8"));
OutputStream resStreamOut = new FileOutputStream(new File("/dir-next-to-jar/some.txt"));
int readBytes;
byte[] buffer = "some string".getBytes();
while ((readBytes = stream.read(buffer)) > 0) {
    resStreamOut.write(buffer, 0, readBytes);
}

This is how I've already successfully loaded a local file next to the JAR into the JAR:

InputStream stream = ThisClassName.class.getClass().getResourceAsStream("/dir-next-to-jar/some.txt");

So, how do I write new data to the same file I loaded into a stream to the JAR?

It seems like the obvious solution would be to reverse the action I took loading the *.text file into the JAR, but this is proving to be impossible.

Note: I use a String as the data type of interest here, but in reality, I'm interested in writing a JSONObject and BufferedImage out from the JAR to a file.

Please help!!!

Community
  • 1
  • 1
ddaaggeett
  • 149
  • 2
  • 10
  • What exactly is the problem with the code that you posted in the first snippet? –  Jan 23 '17 at 20:39
  • i'm not exactly sure. i came up with it by taking bits of this - http://stackoverflow.com/questions/10308221/how-to-copy-file-inside-jar-to-outside-the-jar – ddaaggeett Jan 23 '17 at 20:48
  • Well is it not working? Does it throw an exception? I'm asking *what* the problem is, not *why* :) –  Jan 23 '17 at 22:25

1 Answers1

0

if you have the data as a String, how about using Apache's FileUtils:

https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html#writeStringToFile(java.io.File,%20java.lang.String,%20java.nio.charset.Charset) You can write txt into a file with one line.

Brian Pipa
  • 808
  • 9
  • 23
  • Use of third party libraries incurs a significant penalty: They reduce the portability of the program and are more susceptible to bugs than Java SE. Using a third party library for something that can be done with three lines of code does not seem like a beneficial trade-off to me. – VGR Jan 23 '17 at 21:41
  • by the looks of if, an ApacheV2 library should work fine under a GPLv3 project - https://www.apache.org/licenses/GPL-compatibility.html – ddaaggeett Jan 24 '17 at 01:29