简体   繁体   中英

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();
            }

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();
...

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM