我正在嘗試編寫能夠從給定目錄打開任何.jar文件的程序。在使用Process ps = Runtime.getRuntime().exec("java -jar " + contents[selectInt - 1]);
,其中contents[selectInt - 1]
的典型值將是類似於C:\Users\Kieran\Desktop\CharCount.jar
(我已經測試過並且確實將完整文件路徑提供給jar文件)的情況下,沒有命令提示符窗口彈出並且當前窗口中不顯示任何內容。進入控制檯輸入java -jar C:\Users\Kieran\Desktop\CharCount.jar
工作得很好。完整的代碼如下:在同一個控制檯中調用java並運行jar文件
package listfiles;
import java.util.Scanner;
import java.io.*;
public class ListFiles {
private static Scanner sc = new Scanner(System.in);
private static File folder;
public static void main(String[] args) {
//Set folder to search
String filePath;
final int LENGTH = args.length;
if (LENGTH > 0) {
filePath = args[0];
} else {
System.out.print("File to search (or \"QUIT\" to exit): ");
filePath = sc.next();
if (filePath.equals("QUIT")) {
exit();
}
}
folder = new File(filePath);
//Create an array of folder contents with the extension .jar and print it
File[] contents = folder.listFiles(new JarFilter());
System.out.print("Search in \"" + filePath + "\" found " + contents.length + " result");
if (contents.length != 1) {
System.out.print("s");
}
System.out.print(":\n\n");
int i = 0;
for (File file : contents) {
i++;
System.out.println("[" + i + "] " + file);
}
//Allow the user to run a jar file
int selectInt = 0;
while (true) {
System.out.print("Please select a file number to open or \"QUIT\" to exit: ");
String select = sc.next();
if (select.equals("QUIT")) {
exit();
}
try {
selectInt = Integer.parseInt(select);
} catch(NumberFormatException e) {
continue;
}
if ((selectInt > 0) && (selectInt <= contents.length)) {
break;
}
}
try {
System.out.println("java -jar " + contents[selectInt - 1]);
Process ps = Runtime.getRuntime().exec("java -jar " + contents[selectInt - 1]);
} catch (IOException e) {
System.out.println("Opening .jar file failed.");
exit();
}
}
private static void exit() {
System.out.print("\n\nExiting...\n");
System.exit(0);
}
}
JarFilter只接受.jar文件(和工程)。
我會非常感謝任何可能流失的光線。
編輯:爲CharCount.jar的代碼如下:
package charcount;
public class CharCount
{
public static void main(String[] args)
{
int i = 0;
for (String str : args)
{
System.out.println("\"" + str + "\" has " + str.length() + " characters.");
i += str.length();
}
System.out.println("Total characters: " + i);
System.exit(0);
}
}
你知道一個事實,即在JDK是一個新創建的進程的道路上?你有沒有檢查過程''exitValue()'以確保它實際啓動?您只需要將調用jar文件的部分提取到其自己的主類中,而不需要其他代碼,然後在IDE調試器中單步執行。 –
在調用進程後直接添加一行:'System.out.println(ps.exitValue());'產生一個錯誤:'線程中的異常'main「java.lang.IllegalThreadStateException:進程在java中沒有退出'' .lang.ProcessImpl.exitValue(Unknown Source)''at listfiles.ListFiles.main(ListFiles.java:73)' – Kieran
我會將其他jar的代碼添加到問題中。 – Kieran