简体   繁体   English

如何声明文件夹路径?

[英]How to Declare Folder Path?

I have a desktop application using Swing library. 我有一个使用Swing库的桌面应用程序。 Application is running a batch file. 应用程序正在运行一个批处理文件。 So I created a lib folder in main project directory and put batch file in it. 因此,我在主项目目录中创建了一个lib文件夹,并将批处理文件放入其中。 To run this, I am showing lib\\a.exe to run this. 要运行它,我正在显示lib\\a.exe来运行它。 It is working on my laptop. 它正在我的笔记本电脑上工作。 I exported .jar and put lib folder next to it. 我导出了.jar并将lib文件夹放在它旁边。 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 . 错误消息是:Windows找不到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 找到您的应用程序的jar文件的目录
  2. call a.exe with the correct working directory 用正确的工作目录调用a.exe

You can get the location of the jar with the getJar method below: 您可以使用以下getJar方法获取罐子的位置:

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: 要调用lib \\ a.exe,可以执行以下操作:

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. 但是您的文件路径必须是这样的../lib/a.exe。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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