2015-05-02 53 views
1

我有一個名爲helloDemo的jar,它只是簡單地顯示一個值爲'Hello World'的joption窗格。它工作正常。而我有另一個名爲wrapperDemo的應用程序,我想從中執行這個jar。在java中可以這樣做嗎? Google搜索後嘗試了一些方法,但沒有運氣。我不知道該怎麼做?以下是在庫中添加jar的嘗試。我正在使用netbeans ide。下面是我的嘗試婁:::如何從java中的另一個應用程序運行jar文件

public class WrapperDemo { 
public static void main(String[] args) throws IOException {   
    ProcessBuilder pb = new ProcessBuilder("/wrapperDemo/Libraries", "-jar", "helloDemo.jar"); 
    pb.start(); 
} 

}

+0

如果你想在同一個JVM執行罐子一看這裏[運行一個可執行-JAR文件中之Java的程序 - 使用級裝載機(http://stackoverflow.com/questions/12214678/run-a-executable-jar-file-within-java-program-using-class-loadershttp://stackoverflow.com/questions/12214678/run-a-executable-jar-file-within-java-program-using-class-loaders#12214934) – SubOptimal

+0

@ChetanKinger非常感謝。你的鏈接對我有迴應。但是我不能贊成你,因爲你剛剛評論過。 –

回答

1

考慮Apache Commons Exec實現多平臺發佈機制。

String line = "java -jar /wrapperDemo/Libraries/helloDemo.jar"; 
CommandLine cmdLine = CommandLine.parse(line); 
DefaultExecutor executor = new DefaultExecutor(); 
int exitValue = executor.execute(cmdLine); 
0

這個片段將幫助:

Runtime.getRuntime().exec("java -jar /wrapperDemo/Libraries/helloDemo.jar"; 
+0

哦,可惜的是:1)使用'ProcessBuilder' 2)將'String' arg分解成'String []'args。 - 這是比問題中的代碼更先進(也更脆弱)! –

相關問題