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.

1
  • Can you provide some existing code details about how you are using? Commented May 21, 2019 at 15:47

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.