有 Java 编程相关的问题?

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

OSX中的java运行CMD等效程序?

我使用此代码使Java程序打开一个(可见)CMD窗口:

try {
            String line;
            Process p = Runtime.getRuntime().exec("cmd /C start \"Render\" \"" + myPath + "\\punchRender.cmd\"");
             BufferedReader input =
                    new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((line = input.readLine()) != null) {
            System.out.println(line);
            jLabel7.setText(line);

            }
            input.close();
        } catch (Exception err) {
            err.printStackTrace();
        }

我一直在尝试对OSX终端做同样的事情,这就是我现在所处的位置:

  try {
            String line;
            Process p = Runtime.getRuntime().exec("sh " + myPath + "/punchRender.sh");
             BufferedReader input =
                    new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((line = input.readLine()) != null) {
            System.out.println(line);
            jLabel7.setText(line);

            }
            input.close();
        } catch (Exception err) {
            err.printStackTrace();
        }

到目前为止,没有任何建议?该.sh文件甚至没有运行


共 (5) 个答案

  1. # 1 楼答案

    我想你已经检查过了。sh文件是可执行的,不是吗

  2. # 2 楼答案

    我只需要确保你的shell脚本有执行位,然后传入shell脚本文件名

    Process p = Runtime.getRuntime().exec(myPath + "/punchRender.sh")

    编辑:

    我不太清楚Java是否可以为Unix/Linux设置文件权限,用它来设置执行位或如何转义引号。但会是这样的:

    Process chmod = Runtime.getRuntime().exec("chmod u+x \"" + myPath + "/punchRenderer.sh\"")

  3. # 3 楼答案

    这应该行得通。不仅要运行脚本,还要打开终端:

    Process p = Runtime.getRuntime().exec("open -a /Applications/Utilities/Terminal.app \"" + myPath + " /punchRender.sh\"");

  4. # 4 楼答案

    如果需要新的可见终端窗口,则不能直接运行shell。你需要启动终端,然后运行。命令文件,而不是shell脚本。我不确定将该命令的stdout连接到Java进程有多难。您可能需要想出其他方法将输出输入终端

    顺便说一句,我在家里自己的Mac电脑上的一个课堂上尝试了你的代码,它运行了一次。很好。我正在从命令行运行java类。也许她不在你的道路上

  5. # 5 楼答案

    我建议您将标准错误以及捕获为标准输出,并将其转储。这应该会让你对正在发生的事情有所了解(一般来说,这是一个很好的练习)

    您可能需要在不同的线程中收集标准输出和标准错误,以避免阻塞问题。参见here了解StreamGobbler