Results 1 to 2 of 2
  1. #1
    tjsaker is offline Member
    Join Date
    Nov 2008
    Posts
    1
    Rep Power
    0

    Default Obtaining relative path outside of executable JAR

    Hi, I've Googled until I'm blue on this and no luck. I have an application packaged as an executable JAR. The application needs to be able to reference a predefined lib directory, relative to and outside of itself (the JAR), where users will place JDBC driver JAR's to be dynamically loaded. In order to maintain independence of installation location I would like the application to dynamically obtain the list of JAR files in the lib directory, relative to it's installed location. All of the information I've been able to glean online discusses how to dynamically locate files within the executable JAR itself, not outside of it. Is what I'm wanting to do possible?

  2. #2
    masijade is offline Senior Member
    Join Date
    Jun 2008
    Posts
    2,571
    Rep Power
    9

    Default

    Java Code:
      public static String getPathToJarfileDir(Object classToUse) {
        String url = classToUse.getClass().getResource("/" + classToUse.getClass().getName().replaceAll("\\.", "/") + ".class").toString();
        url = url.substring(4).replaceFirst("/[^/]+\\.jar!.*$", "/");
        try {
            File dir = new File(new URL(url).toURI());
            url = dir.getAbsolutePath();
        } catch (MalformedURLException mue) {
            url = null;
        } catch (URISyntaxException ue) {
            url = null;
        }
        return url;
      }
    Naturally, only works for local (not remote) jarfiles (and not directory based classes), and must be called using an instance of a Class that is contained within that jarfile as the parameter.

    Edit: This returns, of course, the absolute path to the directory containing the jarfile. Modify what is returned to get what you want.
    Last edited by masijade; 11-14-2008 at 07:54 AM.

Similar Threads

  1. executable
    By smooth in forum New To Java
    Replies: 4
    Last Post: 06-14-2008, 06:12 PM
  2. HashMap: Obtaining all values in a collision?
    By markus-sukram in forum New To Java
    Replies: 2
    Last Post: 03-29-2008, 11:25 PM
  3. Executable Java
    By eva in forum New To Java
    Replies: 3
    Last Post: 12-31-2007, 12:38 AM
  4. Executable JAR
    By bugger in forum New To Java
    Replies: 4
    Last Post: 12-05-2007, 06:41 PM
  5. Replies: 1
    Last Post: 11-16-2007, 11:09 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •