0

I know how to check for a file in a specific directory or a specific directory but I can't figure out how to check for a file that is outside of the jar that is being run but in the same directory as it: Test.jar - Ran -> Get location of Test.file Test.file

Answered - Thank you!

This works great;

final Class<?> referenceClass = Client.class;
    final URL url = referenceClass.getProtectionDomain().getCodeSource().getLocation();
    try{
        final File jarPath = new File(url.toURI()).getParentFile();
        System.out.println(jarPath);
    } catch(final URISyntaxException e){
        // etc.
    }

3 Answers3

1

You can create a new file using the createNewFile() operation, get the location of that file and remove the file again. The new file will be generated in the same location as where the jar file is running.

Filip
  • 857
  • 8
  • 19
  • I think createNewFile() will create the file in current working directory of Java. Same, value can be read from `System.getProperty("user.dir");` – Bimalesh Jha Aug 01 '13 at 11:43
  • 'Where the JAR file is running' isn't the same thing as where the JAR file *is*. – user207421 Aug 01 '13 at 11:47
1

A possible solution is presented using ProtectionDomain in this thread: Loading a file relative to the executing jar file

Community
  • 1
  • 1
Bimalesh Jha
  • 1,464
  • 9
  • 17
0

The location of the JAR file is given by Class.getProtectionDomain().getCodeSource().getLocation() for any class that is known to be in that JAR file.

user207421
  • 305,947
  • 44
  • 307
  • 483