Java 項目依賴外部可執行文件(如 Selenium 的 IEDriverServer.exe),打包成 JAR 後無法運行,因 JAR 內無法直接執行嵌套的原生可執行文件。
JAR 包只能包含類文件與資源,不能直接執行其中的 .exe/.dll/.so 文件。 必須在運行時將其釋放到臨時目錄再調用。
IEDriverServer.exe 放入 src/main/resources/drivers/,打包進 JAR。private File extractDriver(String resourcePath, String fileName) throws IOException {
File tempDir = new File(System.getProperty("java.io.tmpdir"), "myapp-drivers");
tempDir.mkdirs();
File target = new File(tempDir, fileName);
if (!target.exists()) {
try (InputStream in = getClass().getResourceAsStream(resourcePath);
FileOutputStream out = new FileOutputStream(target)) {
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) > 0) out.write(buf, 0, len);
}
target.setExecutable(true); // Linux/Mac 需賦予執行權限
}
return target;
}
System.setProperty("webdriver.ie.driver", extractedFile.getAbsolutePath());。launch4j + Inno Setup),將驅動作為獨立文件隨安裝包分發。百度知道 相關回答 提供了類似思路。