有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用JavaFx应用程序中的参数执行Runnable Jar

我需要从JavaFX应用程序运行可执行jar。 我正在尝试以下代码:

public void runJar() {
    try {
        //String serverIp = oRMIServer.getServerIP();
        String arg1 = "\"arg1\"";
        String arg2 = "\"arg2\"";
        String command = "java -jar "  + "path/of/jar.jar " + arg1 + " " + arg2;
        Runtime run = Runtime.getRuntime();
        Process proc = run.exec(command);
    } catch (Exception e) {
        System.out.println("Exception occured "+e);
    }

令人惊讶的是,如果我正在创建一个新类并编写这段代码,它会在我的eclipse中运行,但frm我的Java FX应用程序根本没有运行这段代码。我看不到任何东西看起来像是被跳过了。 有人能帮我从JavaFX应用程序中执行带有参数的java可执行jar吗

虽然我现在用过

String command = "cmd /c start \"\" \"" + classPath + "\\jre\\bin\\javaw.exe\" -jar \"" + classPath + "\\jarName.jar\" " + runTimeArg1 + " " + runTimeArg2;

Runtime run = Runtime.getRuntime();
Process proc = run.exec(command);

在这之后,什么也不会发生。请帮忙


共 (1) 个答案

  1. # 1 楼答案

    确保代码在try-catch中运行,并打印堆栈跟踪。您应该使用String[] command,这样就不会使用字符串连接,并使用ProcessBuilder调用,这样就可以看到子进程的STDOUT/ERR。下面是一个例子:

    try {
        String java = Path.of(System.getProperty("java.home"),"bin", "javaw.exe").toAbsolutePath().toString();
        String[] command = new String[] {java, "-jar", "\\path\\to\\yourName.jar", "runTimeArg1", "runTimeArg2"};
        exec(command); // or Runtime.getRuntime().exec(command); 
    } catch (Exception e) {
        System.out.println("Exception occurred "+e);
        e.printStackTrace();
    }
    
    
    public static int exec(String[] cmd) throws InterruptedException, IOException
    {
        System.out.println("exec "+Arrays.toString(cmd));
    
        ProcessBuilder pb = new ProcessBuilder(cmd);
    
        Path tmpdir = Path.of(System.getProperty("java.io.tmpdir"));
        Path out = tmpdir.resolve(cmd[0]+"-stdout.log");
        Path err = tmpdir.resolve(cmd[0]+"-stderr.log");
        pb.redirectOutput(out.toFile());
        pb.redirectError(err.toFile());
        // OR pb.redirectErrorStream(true);
    
        Process p = pb.start();
        long pid = p.pid();
        System.out.println("started PID "+pid);
        int rc = p.waitFor();
    
        System.out.println("Exit PID "+pid+": RC "+rc +" => "+(rc == 0 ? "OK": "**** ERROR ****"));
        System.out.println("STDOUT: \""+Files.readString(out)+'"');
        System.out.println("STDERR: \""+Files.readString(err)+'"');
        System.out.println();
        return rc;
    }