4

What is the best way to find a path relative to the folder where a java application is "installed"?

I have a class with a static method: public static void saveToFile(String fileName)

When I call it with an absolute path, it works, but what I really want is the relative path to where the application is run from, and a folder.

I have not deployed my application, but right now I want to find a path relative to the (Netbeans) project root, and a folder within called data: ProjectName\data\file.dat. Should I use the File class or make it into a URI or something?

Note that I prefer it to be system-independent and will still work if the application is deployed. Eventually the (relative) pathname will be stored in a properties file.

Sorry if this question is a duplicate, any help is appreciated.

MarioDS
  • 12,895
  • 15
  • 65
  • 121

5 Answers5

5

What is the best way to find a path relative to the folder where a java application is "installed"?

OS manufacturers have been saying for a long time not to save files in the application directory.

Note that I prefer it to be system-independent and will still work if the application is deployed.

Instead put the File in a sub-directory of user.home. User home is where it should be possible to establish a file object that can be read or written. It is also a place that is reproducible across runs, and platform independent.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
2

If you deploying as a jar, its possible to obtain the jar file name and path the current code is working in like this:

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

(from How to get the path of a running JAR file?)

Community
  • 1
  • 1
j13r
  • 2,576
  • 2
  • 21
  • 28
2

Here you go:

String path = System.getProperty("user.dir");
tckmn
  • 57,719
  • 27
  • 114
  • 156
Craig R
  • 21
  • 1
1

To find relative path to current working directory say new File(".").

If you want to know absolute path of current working directory you can write new File(".").getAbsolutePath() or File(".").getAbsoluteFile()`.

I hope this answers your question. I am sorry if I did not understand you correctly.

AlexR
  • 114,158
  • 16
  • 130
  • 208
  • You didn't understand correctly. He wants the program path, not the working directory. – j13r Apr 16 '12 at 18:23
  • I tried by using `"." + File.separator + "data" + File.separator + "file.dat"` And it didn't work... – MarioDS Apr 16 '12 at 18:26
  • Allright I tried it with a File and I printed the absolute path, its **absolutely correct** and it didn't work... It returns `C:\blah\projectName\data\file.dat`as required... – MarioDS Apr 16 '12 at 18:34
  • use File("./filename") . It comes to ../workspace/myWorkingProject/filename – Linh Lino Jun 02 '14 at 22:13
0

To get the absolute path to a file use new File().getCanonicalFile().

new FileOutputStream(new File(".\\target\\dataset.xml").getCanonicalFile())
tak3shi
  • 2,305
  • 1
  • 20
  • 33