Onuray Sahin
Onuray Sahin

Reputation: 4135

How to Declare Folder Path?

I have a desktop application using Swing library. Application is running a batch file. So I created a lib folder in main project directory and put batch file in it. To run this, I am showing lib\a.exe to run this. It is working on my laptop. I exported .jar and put lib folder next to it. It is working on my laptop, but not working on some other laptops. How to fix this?

Error message is: Windows cannot found lib\a.exe.

String command = "cmd /c start lib\\a.exe";
            try {
                Runtime.getRuntime().exec(command);
                increaseProgressBarValue();
            } catch (IOException e) {
                e.printStackTrace();
            }

Upvotes: 1

Views: 2091

Answers (2)

Yordan Borisov
Yordan Borisov

Reputation: 1652

Maybe you have to try if this folder lib exists and if it doesn't than create it with

file.mkdir();

This is a just a checking. But your filepath must be like this ../lib/a.exe.

Upvotes: 0

Maurice Perry
Maurice Perry

Reputation: 32831

You need two things:

  1. find the directory of the jar file of your application
  2. call a.exe with the correct working directory

You can get the location of the jar with the getJar method below:

private static File getJar(Class clazz) throws MalformedURLException {
    String name = clazz.getName().replace('.','/') + ".class";
    ClassLoader cl = Thread.currentThread().getContextClassLoader();
    URL url = cl.getResource(name);
    System.out.println(url);
    if (!"jar".equals(url.getProtocol())) {
        throw new MalformedURLException("Expected a jar: URL " + url);
    }
    String file = url.getPath();
    int pos = file.lastIndexOf('!');
    if (pos < 0) {
        throw new MalformedURLException("Expected ! " + file);
    }
    url = new URL(file.substring(0, pos));
    if (!"file".equals(url.getProtocol())) {
        throw new MalformedURLException("Expected a file: URL " + url);
    }
    String path = url.getPath();
    if (path.matches("/[A-Za-z]:/")) { // Windoze drive letter
        path = path.substring(1);
    }
    return new File(path);
}

To call lib\a.exe, you can do something like this:

File jar = getJar(MyClass.class); // MyClass can be any class in you jar file
File dir = jar.getParentFile();
ProcessBuilder builder = new ProcessBuilder();
builder.command("lib\\a.exe");
builder.directory(dir);
...
Process p = builder.start();
...

Upvotes: 3

Related Questions