gpt4 book ai didi

java - 在同一控制台中从 java 调用并运行 jar 文件

转载 作者:太空宇宙 更新时间:2023-11-04 12:52:00 25 4
gpt4 key购买 nike

我正在尝试编写一个能够从给定目录打开任何 .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进入控制台工作得很好。完整代码如下:

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);
}
}

最佳答案

如果您尝试从 cmd 运行它,您是否尝试过:

Runtime.getRuntime().exec("cmd /c start java -jar FILEPATH");

或者根据您的情况:

Runtime.getRuntime().exec("cmd /c start java -jar" + contents[selectInt - 1]);

----更新----

要保持提示打开,请使用:

Runtime.getRuntime().exec("cmd /c start cmd /k java -jar " + contents[selectInt - 1]);

关于java - 在同一控制台中从 java 调用并运行 jar 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35734774/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com