0

So the problem is I try to read the configuration file that is packed inside the .jar which works fine but then when it comes to writing to the file the file can not be found yet they are using the same

getClass().getResource(Path);

it only seems to work with the input stream.

Here is all the code of my IO class.

package com;

public class IO {

public boolean CheckStream () {
    String LineRead;

    try {

        InputStream IS = getClass().getResourceAsStream("Config.txt");

        InputStreamReader ISR = new InputStreamReader (IS,Charset.forName("UTf-8"));
        BufferedReader BR = new BufferedReader(ISR);

        if ((LineRead = BR.readLine()) != null) {
            BR.close();
            return true;
        }

        IS.close();

    } catch (IOException e) {
        e.printStackTrace();
    }

    return false;
}

public void Write (String Path, String [] ThingsToWrite) throws FileNotFoundException {
    OutputStream Out = new FileOutputStream (getClass().getResource(Path).getPath());
    PrintStream PS = new PrintStream (Out);

    for (int i = 0; i < ThingsToWrite.length; i ++) {
        PS.print(ThingsToWrite[i]);
    }

    PS.close();
}

}

Any Help is greatly appreciated thanks.

Hewiiitt
  • 307
  • 1
  • 12
  • possible duplicate of [Write To file with getResource](http://stackoverflow.com/questions/14446974/write-to-file-with-getresource) – Joe Feb 07 '15 at 13:15

1 Answers1

2

You can't just write to a file within a jar file - it's not a file in the regular sense.

While you could unpack the whole jar file, write the new content, then pack it up again, it would be better to redesign so that you don't need to update the jar file.

For example, you might have a regular local file which is used if it's present, but then fall back to reading from the jar file otherwise. Then you only need to write to the local file.

Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
  • Well the problem is that the user needs to be able to write in a custom Server address for the application to use is there another way of writing this so that the user can set it up once and then it be saved and used by default like some other way of saving that is inside the jar just so they don't have files floating around that they could easily lose. – Hewiiitt Jan 19 '15 at 11:29
  • @Hewiiitt: Not easily, no. Bear in mind that if it's in the jar file, that means that upgrading to a later version of the code will lose the configuration as well. It's best to keep non-default configuration out of jar files. We don't really know your context here, but you *might* want to look at the Preferences API. – Jon Skeet Jan 19 '15 at 11:30