views:

72

answers:

3

I have a swing Java application that preserves a lot of data (you can think of a game and its saves for example). Those data are stored in files rather then in database.

I would like to keep this files near installation files(.jar file) of my application.Some users(like me) are used to delete default application folder of OS when it comes to large and I don't want them to loose their data this way.

Any ideas how to do this easily ? How do I get the folder of the .jar file from program that is executing form that .jar file? Or how do I output files directly into some package? How do I create packages(folders inside jar) dynamically ? Or is there a simple way to distribute Java application in other formats then .jar and then store generated data in installation (sub)folder ?

Thanks for reading

+5  A: 

The code

URL folderURL = ClassLoader.getSystemResource(".");

will provide a URL to the first location searched for resources like the class file you're currently executing.

Stephen Denne
+2  A: 

Here is an example:

package jartest;

import java.io.File;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    private static final Pattern JARURL = Pattern.compile("jar:file:(.*)!.*");

    public static void main(String[] args) {
        try {
            URL url = Main.class.getResource("Main.class");
            Matcher matcher = JARURL.matcher(url.toString());
            if (matcher.matches()) {
                File file = new File(matcher.group(1));
                File dir = file.getParentFile();
                System.out.println(dir);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Maurice Perry
+6  A: 

I would like to keep this files near installation files(.jar file) of my application.Some users(like me) are used to delete default application folder of OS when it comes to large and I don't want them to loose their data this way.

This (and the concept of multi-user systems with no write access to application directories for regular user accounts) is the reason why user data should be kept in the user's home directory, and not anywhere near the app installation folder.

Michael Borgwardt
Well, how do I save data to the user's home directory or whatever is platform default place for them in Java ?
drasto
@drasto: System.getProperty("user.home") will return the directory path.
Michael Borgwardt