简体   繁体   中英

Set a Path for database file in java

I am developing a program that uses a sqlite file as a database. When I compile and test my program I haven't any problem:

Conection c = DriverManager.getConnection(
                    "jdbc:sqlite:/home/mehdi/my_database.sqite");

as you can see in above, the code shows a direct path that set to database file (this path is only in my system). So it works fine, but my problem starts when I create an executable jar file of my program, if I create executable jar file and share it with other users, when they run the executable jar it doesn't work.

My first question: how do I set my database path for an executable jar file in my code? My second question: is it possible for the database to be along side the executable jar? (and i can move my executable jar file with its database)

some_path/my_program_file.jar
some_path/my_database.sqite

The best option is externalizing the database path instead of hardcoding it, and letting the user choose where to put the actual sqlite file.

You could put the sqlite file in the same directory as the program archive, but please note that this does not really help in locating the file from your code, because relative paths are definitely resolved against the JVM (process) working directory, not the location of the JAR:

new File(".").getAbsolutePath()

There are ways to get the location of the JAR:

getClass().getProtectionDomain().getCodeSource().getLocation()

but they are deploy-dependent, so it's not a very robust strategy to rely on.

Most Java program are configured with external files put in well-known locations (like the current JVM directory or a .myapp/conf.properties in the user home), and individual properties can be overridden in the starting command line, as either system properties -Dkey=value or program arguments (there's a library to simplify this)

Java uses relative paths when you do not specify the absolute path. I'm not sure if it works for the DriverManager though. What this means is that if you call jdbc:sqlite:my_database.sqite it should look for my_database.sqite in the folder the jar is executed from. So if the user calls java -jar my_program_file.jar from the folder where the database is it will work. If the user calls the jar from another location it won't. To fix that, you have to grab the path where the jar is located, like so:

return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());

This was showcased in another SO post .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM