如何将另一个命令发送到现有进程?

时间:2016-02-07 16:22:36

标签: java minecraft

我得到了以下启动Minecraft服务器的代码:

public class App {

    public static void main(String...args) throws Exception {
        final ProcessBuilder processBuilder = new ProcessBuilder();
        processBuilder.directory(new File("C:/Users/trudler/Desktop/New folder (4)/"));
        processBuilder.command("java", "-jar", "server.jar");
        Process process = processBuilder.start();

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;

        System.out.printf("Output of running %s is:", Arrays.toString(args));

        while ((line = br.readLine()) != null) {
          System.out.println(line);
        }
    }
}

我想做每日备份,所以我需要发送"停止"每天命令,以确保在我进行备份时不会触及文件("然后再次启动"服务器)。

我该怎么做?

我是使用processBuilder.command("stop");尝试过的,但这似乎无法发挥作用。

1 个答案:

答案 0 :(得分:3)

我认为您希望将命令发送到现有流程,因此我认为这正是您所寻找的:

Execute external program using ProcessBuilder and provide input

public class App{

   public static void main(String... args) throws Exception {
      while (true) {
         Process process = Example.startMinecraft(args);
         // Stops for sixty seconds
         Thread.sleep(1000 * 60);

         BufferedWriter out = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
         out.write("stop");

         // Wait for the process to stop
         process.waitFor();

         // Now start your Backup
         Process backupProcess = Example.startBackup();
         backupProcess.waitFor();

         // After your backup completed your minecraft server will start again
      }

   }

   private static Process startMinecraft(String... args) throws IOException {
      final ProcessBuilder processBuilder = new ProcessBuilder();
      processBuilder.directory(new File("C:/Users/trudler/Desktop/New folder (4)/"));
      processBuilder.command("java", "-jar", "server.jar");
      Process process = processBuilder.start();

      InputStream is = process.getInputStream();
      InputStreamReader isr = new InputStreamReader(is);
      BufferedReader br = new BufferedReader(isr);

      Thread t1 = new Thread(() -> {
         try {
            String line;
            System.out.printf("Output of running %s is:", Arrays.toString(args));
            while ((line = br.readLine()) != null) {
               System.out.println(line);
            }
         } catch (IOException e) {
            // Do something when the Exception is thrown
         }
      });
      t1.start();

      return process;
   }

   private static Process startBackup(){
      // Here you have to build your backup process
   }
}

如果你在linux机器上,我建议在/etc/init.d/中使用一些脚本,并在cron作业中使用这个脚本重启命令。