Answer the question
In order to leave comments, you need to log in
How to write to a file in a jar-nickname from a class located in the same jar-nickname?
Hello. Faced a problem. Wrote a simple console game. Made a top list of players there. I save the table itself in a TreeSet (where each row is an object with its own fields-columns of the table). Then I serialize this table to a file. When the game starts, the table of players is loaded from the file (deserialization occurs). When I specify this path:
"." + File.separator + "src" + File.separator + TopList.class.getPackage().getName().replace(".", File.separator) + File.separator + "TopListOfPlayers.dat";
private static final String fileTopList = File.separator +
TopList.class.getPackage().getName().replace(".", File.separator) +
File.separator + "TopListOfPlayers.dat";
private final URL urlFileTopList = getClass().getResource(fileTopList);
...
try (ObjectInputStream objectInput = new ObjectInputStream(urlFileTopList.openStream())) {
topList = (Set<TopListEntry>) objectInput.readObject();
}
Answer the question
In order to leave comments, you need to log in
Make it easier.
Keep the starting top list in the jar file with the game. When you first need to write to it - create in a strictly defined place (in the user's home directory, next to the jar'nickname, etc) a file with an updated top of the players.
The process of loading the top will look quite simple:
1) Check for the presence of a file with the top players in the selected location.
2) If not found - load from jar file.
And yes - why do you need top players? If you want players from different places to measure the strength of the heroic - you need to store this top centrally - for example, on a single server. If the storage is strictly local - generate a fictitious top at the first start next to the jar file and update as the games progress.
Until I found this: link . And apparently it's impossible. You can only write to some external file. This is inconvenient, because it is easier to distribute the program as a single jar file. The way out is to pack a folder with a jar-nickname and an external file into an archive, and distribute the program in this form. (In my case, I can simply create a top-list file every time in the same folder where the jar-nick is located, and work with this created file.)
PS I just don’t understand yet how to work with the file from the IDEA then, think....
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question