运行时如何在Jar文件中修改文本文件? [英] How can I modify a text file inside a Jar file while runtime?

查看:108
本文介绍了运行时如何在Jar文件中修改文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,正如问题所说,那怎么可能?
此文件是我的proyect结构(我正在使用eclipse)。

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

当导出为Jar时,我可以使用以下代码通过控制台访问和打印 root.ini内容,但是,如何在运行时写入该文件?

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?

此方法从'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);
}

我实际上想做的是从JTextField获取一些文本,并将其保存到 root.ini文件中。

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();
    }
}

并抛出此错误


C:\Users\Francisco\Desktop\tds> java -jar TDS.jar
线程 AWT-EventQueue-0中的异常 java.lang.IllegalArgumentException:URI不是java.io.File处的分层
。(未知源)main处的$ b $b。Configuracion.writeRoot(Configuracion.java:99)主要处的
。 Configuracion.access $ 1(Configuracion.java:95)

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)


推荐答案

您不能更改任何jvm当前使用的jar的内容。该文件被操作系统锁定,因此无法更改。

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.

我建议将此文件写入jar文件之外。例如相对于当前工作目录的 / conf 目录中。

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

这篇关于运行时如何在Jar文件中修改文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆