1

Summary - this code:

File f = new File("dbFile.dat");
f.getAbsolutePath();

Returns:

/Applications/dbFile.dat

The problem is that my application's resources (3d party jars for instance) are located in "Applications/Foobar.app/...".

How to get the path to my install folder without hardcoding anything?

Details:

I'm using a 3d party library for which I need to provide a filename:

ls = new LookupService("dbFile.dat");

When distributed, this file is placed in the root of my install folder, next to the executable files - works great on Windows.

However, on Mac I get a FNF exception because the library isn't searching in the correct location:

java.io.FileNotFoundException: dbFile.dat (The system cannot find the file specified)
    at java.io.RandomAccessFile.open(Native Method)
    at java.io.RandomAccessFile.<init>(Unknown Source)
...
Arjan
  • 22,808
  • 11
  • 61
  • 71
Buffalo
  • 3,861
  • 8
  • 44
  • 69
  • Is the file a resource file that is packaged and deployed together with your application? Then you should use a class loader for loading it. – Seelenvirtuose Aug 07 '13 at 11:17
  • I can't do that. The library I'm using only accepts a String parameter which it then uses to access the file. – Buffalo Aug 07 '13 at 12:02
  • 1
    Maybe your are looking for: File f = new File(System.getProperty("user.dir"), "dbFile.dat"); ? Of course, the current working directory must be correctly set at startup time. – Seelenvirtuose Aug 07 '13 at 12:02

2 Answers2

1

Try this:

URL myClass = MyClass.class.getResource("MyClass.class");
System.out.println(myClass.getPath());

This will print out something like this:

file:/home/mike/test.jar!/MyClass.class

You can parse out what you need from that.

Mike Thomsen
  • 36,828
  • 10
  • 60
  • 83
0

I've found that the "foobar.app/.../dbFile.dat" part of the "/Applications/foobar.app/.../dbFile.dat" path is defined in an Ant build file and therefore probably not subject to change by the user at install time as I originally thought, so I used:

String pathToUse = PlatformDetector.IsMacOS() ? "/Applications/foobar.app/.../dbFile.dat" : "dbFile.dat";     
Buffalo
  • 3,861
  • 8
  • 44
  • 69