[英]How to Declare Folder Path?
我有一个使用Swing库的桌面应用程序。 应用程序正在运行一个批处理文件。 因此,我在主项目目录中创建了一个lib
文件夹,并将批处理文件放入其中。 要运行它,我正在显示lib\\a.exe
来运行它。 它正在我的笔记本电脑上工作。 我导出了.jar并将lib文件夹放在它旁边。 它可以在我的笔记本电脑上工作,但不能在其他笔记本电脑上工作。 如何解决这个问题?
错误消息是:Windows找不到lib\\a.exe
。
String command = "cmd /c start lib\\a.exe";
try {
Runtime.getRuntime().exec(command);
increaseProgressBarValue();
} catch (IOException e) {
e.printStackTrace();
}
你需要两件事:
您可以使用以下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);
}
要调用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();
...
也许您必须尝试是否存在此文件夹库,如果不存在,则使用
file.mkdir();
这只是一个检查。 但是您的文件路径必须是这样的../lib/a.exe。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.