Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a file relative to the executing jar file

The question says it all.

The specialty in my case is that the current working directory is not the location of the jar file but c:\Windows\system32 (My jar file is started by windows using the right-click-menu, i want to pass a folder's path as a parameter to the jar).

Now I want to load a configuration file called config.xml that is in the same folder as the jar. The purpose of the file is, of course, to provide settings for the jar. It is important for me that the xml file is outside of the jar file for easy editing.

I'm having a hard time loading that file. Windows executes the line

cmd /k java -jar D:\pathToJarfile\unpacker-0.0.1-SNAPSHOT-jar-with-dependencies.jar

Calling the whole thing with cmd /k leaves the windows command prompt open so that I can see the jar's output.

I cannot use new File(".") or System.getProperty("user.dir") for the relative path as these functions return C:\Windows\system32\. and C:\Windows\system32, respectively (which is the working folder for everything that windows executes AFAIK).

I've had no success with Launcher.class.getResourceAsStream("/../config.xml") either. Since that path begins with /, searching starts at the root node of the jar. Going to ../config.xml point exactly to that file, but the call returns null.

Can someone point me in the right direction? I'm really stuck here. This file loading stuff really bugs me everytime...

Requirements by myself:

  • I don't want to hardcode the path in the java source code
  • I don't want to pass the file's path as a parameter to the java -jar call (neither as a param to the main(String[] args) nor using -Dpath=d:\... to set a system property)

In addition to the original problem, I had a hard time to have maven2 place Class-Path: . into the MANIFEST.MF (The solution that BalusC posted) when using jar-with-dependencies. The problem was that the line appeared in the regular jar's MANIFEST file, but not the jar-with-dependencies.jar's MANIFEST file (2 jar files are generated). For anyone who cares how i did it:

<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <version>2.2-beta-5</version>
    <configuration>
      <archive>
        <manifest>
          <mainClass>${mainClass}</mainClass>
          <addClasspath>true</addClasspath>
          <!--at first, i tried to place the Class-Path entry
              right here using <manifestEntries>. see below -->
        </manifest>
      </archive>
      <descriptorRefs>
        <descriptorRef>jar-with-dependencies</descriptorRef>
      </descriptorRefs>
    </configuration>
    <executions>
      <execution>
        <goals>
          <goal>attached</goal>
        </goals>
        <phase>package</phase>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
          <archive>
            <manifest>
              <mainClass>${mainClass}</mainClass>
            </manifest>
            <!--this is the correct placement -->
            <manifestEntries>
              <Class-Path>.</Class-Path>
            </manifestEntries>
          </archive>
        </configuration>
      </execution>
    </executions>
  </plugin>
like image 838
f1sh Avatar asked Sep 02 '10 13:09

f1sh


People also ask

Why are my jar files not executing?

If you can't run jar files on your Windows 10 PC, you might need to reinstall Java Runtime Environment. When JAR files are not opening, another great method is to simply use a universal file opener. Alternatively, some reported that turning your JAR file into a BAT file worked perfectly.


1 Answers

Here is one possible solution using Class.getProtectionDomain():

final Class<?> referenceClass = YourMainClass.class;
final URL url =
    referenceClass.getProtectionDomain().getCodeSource().getLocation();

try{
    final File jarPath = new File(url.toURI()).getParentFile();
    System.out.println(jarPath); // this is the path you want 
} catch(final URISyntaxException e){
    // etc.
}

YourMainClass can be replaced by any class in your jar.


From the Class.getProtectionDomain() docs:

Returns the ProtectionDomain of this class.
If there is a security manager installed, this method first calls
the security manager's checkPermission method with a
RuntimePermission("getProtectionDomain") permission to ensure it's
ok to get the ProtectionDomain.

Returns:
  the ProtectionDomain of this class
Throws:
  SecurityException - if a security manager exists and its
  checkPermission method doesn't allow getting the ProtectionDomain.
like image 107
Sean Patrick Floyd Avatar answered Sep 18 '22 12:09

Sean Patrick Floyd