【问题标题】:Using Java to run Command Line commands in order使用Java按顺序运行命令行命令
【发布时间】:2011-09-15 14:16:56
【问题描述】:

我正在编写一个程序,该程序需要能够通过命令提示符打开和终止 Minecraft 服务器。到目前为止我的代码是这样的:

Runtime.getRuntime().exec("cd ./Server"); //go to the server directory
Process server = Runtime.getRuntime().exec("java -Xmx1024M -Xms1024M -jar minecraft_server.exe nogui"); //run minecraft server in nogui mode
Thread.sleep((long)(1000*60*.5)); //wait 30 seconds
Runtime.getRuntime().exec("stop"); //terminate the server
Thread.sleep((long)(1000*60*.5)); //wait 30 seconds
server.destroy(); //forcibly terminate the server assuming it hasn't already
System.exit(0);

这只是我想出的基本逻辑代码。我曾尝试使用 BufferedWriters,但它们只是不起作用,即使执行 cd 命令也会出错。我正在使用位于 minecraft.net/download.jsp 的 Minecraft_Server.exe。 “停止”命令在进程处于活动状态时运行,并告诉程序保存服务器然后终止。我是否需要以某种方式使用线程。请帮忙:)我已经花了几个小时试图找到答案,我只是一无所知哈哈。

【问题讨论】:

    标签: java command-line process executable minecraft


    【解决方案1】:

    我认为您的“cd ./Server”命令会在这里丢失上下文,因为下一次调用 exec 不会获得第一次调用的结果。换句话说,对 exec 的每次调用都完全独立于对 exec 的其他调用。

    尝试将其中的一些放在 shell 脚本中,然后简单地执行脚本。如果您仍然通过命令行控制服务器,那么这并不比您已经尝试过的复杂。

    【讨论】:

      【解决方案2】:

      您可能需要查看 ProcessBuilder (here),您可以在其中指定将用于您要执行的所有命令的工作目录。

      【讨论】:

        【解决方案3】:

        每个命令都作为一个单独的进程运行。

        您的“cd ./Server”对您运行的命令没有影响。

        你有一个叫做 stop 的命令行程序吗?

        我会写

        Thread.sleep(30 * 1000); // 30 Seconds.
        

        我不会调用 System.exit(0);

        【讨论】:

          【解决方案4】:

          要在特定目录中运行命令,请使用特殊版本的 exec

          public Process exec(String command, String[] envp, File dir)
          

          dir 是进程的工作目录

          【讨论】:

            【解决方案5】:

            尝试将命令放在字符串数组中:

            String[] cmd = { "cd","./Server" };
            

            String[] cmd2 = {"java", "-Xmx1024M", "-Xms1024M", "-jar", "minecraft_server.exe", "nogui"}

            那就试试

            Runtime.getRuntime().exec(cmd); //go to the server directory
            Process server = Runtime.getRuntime().exec(cmd2); //run minecraft server in nogui mode
            Thread.sleep((long)(1000*60*.5)); //wait 30 seconds
            Runtime.getRuntime().exec("stop"); //terminate the server
            Thread.sleep((long)(1000*60*.5)); //wait 30 seconds
            server.destroy(); //forcibly terminate the server assuming it hasn't already
            System.exit(0);
            

            由于您没有引用要停止的内容,因此 stop 也不会执行任何操作。

            【讨论】:

            • 那行不通。这两个命令仍将作为单独的进程执行。
            猜你喜欢
            • 2017-06-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2010-11-23
            • 2011-11-13
            • 2020-07-12
            • 1970-01-01
            相关资源
            最近更新 更多