背景:我正在编写一个游戏(作为可执行 jar),我的游戏的一部分是一个首选项对话框,您可以在其中设置对手名称和影响游戏进展的不同变量等内容。我认为如果在退出时保存这些内容就好了,这样下次您加载应用程序时它就会记住您之前设置的内容。
为此,我将变量写入 jar 中的 txt 文件,然后在您开始新游戏时从中读取。这在 eclipse 中一切正常,但是当我导出到 jar 时,它根本不起作用。这是我用来读取文件的代码。它位于一个名为“Util”的类中,并在其他地方调用,但我尝试在需要的地方创建非静态方法并使用 getClass() 而不是 Util.class,但仍然没有运气:
public static List<String> getListFromFile()
{
URI fileUri = null;
try
{
fileUri = Util.class.getResource("/gameplayPreferences.txt").toURI();
LoggingDialog.append("\nFileUri is " + fileUri, true);
}
catch (URISyntaxException e)
{
e.printStackTrace();
LoggingDialog.append(e.toString(), true);
}
Path gameplayPreferencesPath = Paths.get(fileUri);
LoggingDialog.append("\ngameplayPreferencesPath is " + gameplayPreferencesPath, true);
Charset charset = Charset.forName("US-ASCII");
try
{
List<String> list = Files.readAllLines(gameplayPreferencesPath, charset);
return list;
}
catch (IOException x)
{
x.printStackTrace();
LoggingDialog.append(x.toString(), true);
}
return null;
}
我放入 LoggingDialog 来帮助我找出问题所在。在这种情况下,我看到“FileUri is rsrc:gameplayPreferences.txt”,没有任何其他内容,所以我假设当我尝试将其转换为路径时,我得到一个 NPE 或类似的东西。
文件gameplayPreferences.txt位于一个名为“resources”的单独资源文件夹中,该文件夹位于我的构建路径的顶部。我不明白的是,我这里也有图像文件,当我使用 getClass().getResource() 创建图像图标时,这工作正常 - 我可以导出到 jar 并且所有图像都正确显示。那么,为什么当我导出到 jar 时,使用相同的方法会破坏 txt 文件,以及如何修复它?
最佳答案
To do this I am writing the variables to a txt file within the jar
因此修改 jar 是不正确的。您需要使用其他东西来存储用户偏好、保存的游戏数据、分数等。
一种方法是使用首选项 API。请参阅What is the best way to save user settings in java application?了解更多信息。
关于java - getClass().getResource() 不适用于 .txt 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20029527/