Get location where Java code is running from

I have a Java swing application that saves a lot of data (for example, you might think about a game and saving it). This data is stored in files, not in a database.

I would like to save these files next to the installation files (.jar file) of my application. Some users (like me) are used to delete the default application folder of the OS when it becomes large, and I do not want them to lose their data in this way.

Any ideas how to do this easily? How to get the .jar file folder from a program that runs a form that is a .jar file? Or how can I output files directly to some kind of package? How to create packages (folders inside banks) dynamically? Or is there an easy way to distribute a Java application in other formats, then .jar, and then save the generated data in the installation folder (under)?

Thanks for reading

+3
source share
4 answers

I would like to save these files next to the installation files (.jar file) of my Some users (for example, I) are used to remove the default application from the OS folder when it comes to large ones and I don’t want them to data this way.

( ) , , - .

+6

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

URL- , , , .

+5

:

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();
        }
    }
}
+2

jar

(, )

public String path()
{
URL url1 = getClass().getResource("");
String ur=url1.toString();
ur=ur.substring(9);
String truepath[]=ur.split("myjar.jar!");
truepath[0]=truepath[0]+"myfolder/";
truepath[0]=truepath[0].replaceAll("%20"," ");
return truepath[0];
}//This method will work on Windows and Linux as well.
//You can alternatively use the following line to get the path of your jar file
//classname.class.getProtectionDomain().getCodeSource().getLocation().getPath();

, jar D:\Test\dist

() /D:/Test/dist/myfolder/

"myfolder" , jar.

Inno http://www.jrsoftware.org/isdl.php

" script script Wizard >

jar ( "", jar)

"myfolder" " " ( )

.

0

Source: https://habr.com/ru/post/1742095/


All Articles