1

Well as the question says, How is that possible? This file is my proyect structure (I'm using eclipse).

enter image description here

When exported as Jar, I can access and print the "root.ini" content through console with the code below but, How can I write to that file while runtime?

This method is called from 'Main.java'

private void readRoot(){
    InputStream is = getClass().getResourceAsStream("/img/root.ini");
    BufferedReader br = null;

    br = new BufferedReader(new InputStreamReader(is));
    String path = "";

    try {
        path = br.readLine();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println(path);
}

What I'm actually trying to do is get some text from a JTextField, and save it to "root.ini" file.

So when I try to write to that file like this

private void writeRoot() {
    URL u = getClass().getResource("/img/root.ini");
    File f = null;
    try {
        f = new File(u.toURI());
        FileWriter fw = new FileWriter(f.getAbsolutePath());
        BufferedWriter bw = new BufferedWriter(fw);

        bw.write("Sample text"); //This String is obtained from a TextField.getText();

        bw.close();
        fw.close();
    } catch (URISyntaxException | IOException e) {
        e.printStackTrace();
    }
}

And throws me this error

C:\Users\Francisco\Desktop\tds>java -jar TDS.jar Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: URI is not hierarchical at java.io.File.(Unknown Source) at main.Configuracion.writeRoot(Configuracion.java:99) at main.Configuracion.access$1(Configuracion.java:95)

Fran
  • 521
  • 4
  • 20
  • 1
    A file inside a .jar is not an actual File. `new File` will never work. And as others will tell you, files inside a .jar are read-only. If you want to write a new version, write it somewhere else (temp file, user configuration directory, etc.), and use the file in the .jar as a fallback when that local file does not exist. – VGR Jan 28 '16 at 21:32

1 Answers1

1

You can't change any content of a jar which is currently used by a jvm. This file is considered locked by the operating system and therefore can't be changed.

I suggest to write this file outside your jar file. e.g. in a /conf directory relative to the current working dir.

Marcinek
  • 2,144
  • 1
  • 19
  • 25