0

Part of my (java) code needs to access a database. When opening a connection it checks if the actual database file exists (I use sqlite). I want to make my code portable, so I want to avoid hard coding the path of the database file. Is there anyway in java to get the path of the .java file? Because I know exactly where the database is from the .java file accessing it.

I've tried using current directory with File but it doesn't give me the path of the actual .java file. When I use android studio the current directory is different than when I simply use a terminal.

franchar
  • 21
  • 5

1 Answers1

1

The best way to get the path information would be using Paths and Path class from the java.nio. You can input an absolute path or relative path to the Paths.get(String str) to get the Path.

To get the project directory, you can use:

Paths.get(System.getProperty(“user.dir”))
Paths.get(“”) 

It will get the complete absolute path from where your application was initialized.

The Paths.get() method will return a Path Object, on which you can call toString() or toUri() to get the path. Hope this helps.

Javadocs - Paths

chakwok
  • 980
  • 8
  • 21
  • 1
    that depends how he runs the application, from IDE there can be project folder as working dir, otherwise it could be loc of .java file or even i v seen the location of JDK – user8426627 May 21 '19 at 16:55