[英]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.