gpt4 book ai didi

java - 文件写入jar中的资源文件夹

转载 作者:行者123 更新时间:2023-12-04 10:35:58 24 4
gpt4 key购买 nike

我的 java swing 项目中有一个资源文件夹(文件),其中包含一个文本文件(users.txt),我正在将数据读取和写入该文本文件。
当我将它导出为 jar 文件时,从该文件读取就可以了,但是写入文件是有问题的。
我正在以这种方式从文件中读取

InputStream in1 = getClass().getResourceAsStream("/files/users.txt"); 
BufferedReader reader1 = new BufferedReader(new InputStreamReader(in1));

在 jar 文件中读取完全正常
在代码下面的同一个文件中写入(这是 jar 文件的问题)
    File file = new File("src/files/users.txt"); 
FileWriter fw = new FileWriter(file,true);
fw.write(data+"\n");
fw.close();

请帮助我如何使用 jar 文件写入资源文件夹中的文件。
谢谢!

最佳答案

正如评论已经说过的,JAR 中的文件被认为是只读的。

您必须在某个用户或基于安装目录的位置(或用户选择的位置)创建一个文件。

如果您有预配置的数据,则至少有 2 个选项:

  • 使用某种打包工具(也可以是 ZIP 文件)将文件与 JAR 文件一起发送。对于 ZIP 文件,如果您使用的是 Maven,请查看 Maven Assembly Plugin。
  • 从 JAR 中提取文件。

  • 对于后一个用例,我编写了一些实用程序类:
    public void extractResource(String resourcePathString, Path targetDirPath) throws IOException, URISyntaxException {  
    URI jarURI = JarFiles.getJarURI(SomeClassInTheJar.class);
    try (FileSystem jarFS = JarFiles.newJarFileSystem(jarURI)) {
    Path resourcePath = jarFS.getPath(resourcePathString);

    CopyFileVisitor.copy(resourcePath, targetDirPath);
    }
    }

    CopyFileVisitor 的帮助下您可以轻松地从/到 JAR 或 ZIP 文件中递归地提取/添加目录,因为 CopyFileVisitor 使用 PathUtils因此可以跨文件系统工作。

    JarFiles.getJarURI获取类的 JAR URI。

    有关更多信息,请查看教程: https://www.softsmithy.org/softsmithy-lib/lib/2.1.1/docs/tutorial/nio-file/index.html#ExtractJarResourceSample

    该库是开源的。您可以从 Maven 中心获取它:
            <dependency>
    <groupId>org.softsmithy.lib</groupId>
    <artifactId>softsmithy-lib-core</artifactId>
    <version>2.1.1</version>
    </dependency>

    关于java - 文件写入jar中的资源文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60183638/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com