我的 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 Central 获取它:
<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/