0

I've been looking for hours, looking through previous questions on all kind of forums, but i still didn't get it to work.

I have a tetris sort of game (it used pentominoes instead of tetrominoes). I want to save a highscore list. I have a text file in the same folder as my jar file (my exported project from eclipse), and i want to be able to read a few lines (Strings and integers) from this file, and i want to override the data in the file at the end of the program.

I'm having huge problems with the paths to the file and making it work in diffrent directories...

I would appreciate any help! thanks in advance

  • 3
    It sounds like you probably have some code which doesn't work... you should include that in your post. – Jon Skeet Oct 16 '14 at 18:54
  • 2
    I don't think the program should be modifying its own JAR. Why does the high score list need to be shipped with the JAR at all? It belongs in a user data folder. – Matt Ball Oct 16 '14 at 18:55
  • @MattBall The text file is saved in the same folder of the JAR file. Not in it. – spongebob Oct 16 '14 at 20:02

3 Answers3

0

You should save data to appdata space, no to same folder as jar file. You can get path of this space by calling System.getenv("APPDATA"). So the program can look like this:

String path = System.getenv("APPDATA") + File.separator + "best_scores.txt";
try (BufferedWriter bw = new BufferedWriter(new FileWriter(path)))
{
    for(String s : rowsToSave) {
        bw.write(s);
    }
}
catch (Exception e)
{
        // ...
}
MaKri
  • 190
  • 1
  • 8
0

If using an absolute path location is an option, you can do that. But, not a good practice.

If the JAR's directory is on the classpath, see How to really read text file from classpath in Java.

If the JAR's directory is the current working directory new File("highscores.txt") should do the trick.

You really need to consider your target execution environment and be sure you're using something transportable.

Have you considered alternative formats such as the preferences API which might be more portable (i.e. non-Windows) than APPDATA in @MaKri's answer.

Community
  • 1
  • 1
Jacob Zwiers
  • 1,092
  • 1
  • 13
  • 33
0

In my case i think it's perfect to use the answer of MaKri,

Because the highscore list doesn't need to be portable.

If someone gets the game, his highscores are empty so it creates the file at appdata.

If there's allready one then I read it, and i can print to it.

I used PrintWriter and Scanner however, just because i'm familiar with these now.

Thank you guys!

  • By portable, I meant other Operating Systems besides Windows. See: http://stackoverflow.com/questions/6561172/find-directory-for-application-data-on-linux-and-macintosh Glad MaKri's answer works for you. Don't forget to mark it "accepted". – Jacob Zwiers Oct 20 '14 at 14:33