3

I have made a java applet/application game that should save levels that the user can create to their local machine. I say applet/application because it can run either as an application or as an applet. Currently I am using this to write the file:

BufferedWriter bf = new BufferedWriter(new FileWriter("Circles/levels/level.txt"));
for (int i = 0; i < lines.size(); i++) {
    bf.write(lines.get(i));
    bf.newLine();
}

lines is an arraylist with the lines to write to the file.

and

FileReader fr = new FileReader("Circles/levels/level.txt");
        BufferedReader bf = new BufferedReader(fr);
        lines = new ArrayList<String>();
        while (true) {
            String line = bf.readLine();
            if (line == null) {
                break;
            }
            lines.add(line);
        }
        bf.close();

to read the file. Those are surrounded in try/catch loops, I am just showing what I have to.

This works ok, but it seems to be a completely different location on different operating systems, and the application stores in a different location as the applet.

I would like a way to get an absolute path to a place to save levels that would not change no matter where the java program is being run from, and would be the same if you ran it as an application and as an applet. Also it would be nice to have this work on all operating systems (linux, windows, mac).

4

1 回答 1

6

There is no location at all for applets to save data, so if you want to be running as an applet, you have to avoid that, quite simply. The applet sandbox prevents filesystem access completely. You'd need to call on the server to save your data instead.

As for stand-alone applications, I'm also sorry to say that there is no completely generally acceptable convention. However, creating a dotfile directory in the user's home directory is often considered acceptable practice on both Linux, OSX and Windows:

public static final File savedir = new File(new File(System.getProperty("user.home")), ".yourgame");

Then, derive your filenames from that:

FileReader fr = new FileReader(new File(savedir, "level.txt"));

Although it works, it's not exactly what Windows programs would normally do, however.

于 2013-01-01T02:25:07.973 回答