Background: I'm in the process of writing a game (as an executable jar) and part of my game is a preferences dialog where you can set things like the opponent names and different variables that affect how the game progresses. I decided it would be nice if these were saved on exit so the next time you loaded the application it would remember what you had set up before.
To do this I am writing the variables to a txt file within the jar, then reading from that when you start a new game. This is all working fine through eclipse, but when I export to a jar it doesn't work at all. This is the code I'm using to read the file. It's in a class called 'Util' and is called elsewhere, but I've tried making non-static methods where it's needed and using getClass() rather than Util.class and I've still had no luck:
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;
}
The LoggingDialog is something I've put in to help me figure out where problems are occuring. In this case, I see "FileUri is rsrc:gameplayPreferences.txt" and nothing further, so I assume that when I try to convert it to a Path I am getting a NPE or something similar.
The file gameplayPreferences.txt is in a separate resource folder called 'resources', which is at the top of my build path. The thing that I don't understand is that I also have image files in here, and when I use getClass().getResource() to create image icons this is working fine - I can export to jar and all the images display correctly. Why, then, does using the same method break for the txt files when I export to a jar, and how can I fix it?