【发布时间】:2019-03-26 04:02:09
【问题描述】:
当我的程序以两种不同的方式运行时,我无法写入文本文件。当作为 jar 或从 NetBeans 运行时,我可以让它正常工作,但不能同时运行。
我将资源文件夹添加为 Netbeans 中的源包,这导致我的程序在 IDE 中正常工作,但在作为 jar 运行时不能正常工作。如果我没有将资源文件夹作为源包,而是将它放在我的项目根文件夹中,它会从 jar 中正确运行,但不能在 IDE 中运行。我正在尝试将我的程序转换为 java web start 应用程序,因此我希望它可以双向运行,但如果没有必要,请告诉我。
我首先要弄清楚我的代码是否从 jar 中运行,以便将来可以分离我的逻辑。就目前而言,无论哪种方式都是相同的逻辑。此代码在 IDE 中有效,但从 jar 运行时不会保存。 FILEPATH 是两个高分文件之一的路径,它看起来像“data/classichighscores.txt”。这 temp 文件是已在同一目录中创建的空文本文件。
/**
* saves the data to its own text file.
*/
public void save() {
File dataFile = null;
File tempFile = null;
String className = this.getClass().getName().replace('.', '/');
String classJar = this.getClass().getResource("/" + className + ".class").toString();
if (!classJar.startsWith("jar:")) {
dataFile = new File(ClassLoader.getSystemResource(FILEPATH).getFile());
tempFile = new File(ClassLoader.getSystemResource("data/myTempFile.txt").getFile());
} else {
dataFile = new File(ClassLoader.getSystemResource(FILEPATH).getFile());
tempFile = new File(ClassLoader.getSystemResource("data/myTempFile.txt").getFile());
}
try {
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(tempFile), "UTF-8"));
for (String line : FILEDATA) {
bw.write(line);
bw.newLine();
}
bw.close();
dataFile.delete();
tempFile.renameTo(dataFile);
tempFile.createNewFile();
} catch (IOException ex) {
System.err.println(tempFile.toString());
System.err.pritnln(dataFile.toString());
我过去也更改了我的 xml 文件和清单文件,这可能与我的问题有关。我把这段代码放进去让我的 jar 文件和资源在同一个分发文件夹中。
<?xml version="1.0" encoding="UTF-8"?>
<project name="TheLostWand" default="default" basedir=".">
<description>Builds, tests, and runs the project TheLostWand.</description>
<import file="nbproject/build-impl.xml"/>
<!--adding resources to dist folder-->
<target name="-post-jar">
<mkdir dir="${dist.dir}/resources"/>
<copy todir="${dist.dir}/resources">
<fileset dir="${basedir}/resources" />
</copy>
</target>
</project>
我添加了 Class-Path 行。
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build
Class-Path: resources/
我希望我的文本文件能够以更高的分数进行编辑和保存。从 IDE 运行时它可以正常工作,但从 jar 运行时不能正常工作。我可以从源包中删除我的资源文件夹,它可以从 jar 中工作,但不能从 IDE 中工作。
【问题讨论】:
标签: java jar text-files read-write