How can I modify a text file inside a Jar file while runtime? [duplicate]

感情迁移 提交于 2019-12-08 07:37:06

问题


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

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)


回答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.



来源:https://stackoverflow.com/questions/35072320/how-can-i-modify-a-text-file-inside-a-jar-file-while-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!