繁体   English   中英

Java Runtime.exec 可以另一个使用标准输入的 java 程序吗?

[英]Can Java Runtime.exec another java program that uses stdin?

我遇到了一个问题,当使用 Java Runtime 运行另一个 java 程序时,该程序冻结,因为其他程序需要标准输入。 使用 Runtime exec() 执行另一个 java 程序后处理标准输入出现问题。

这是我无法工作的示例代码。 这甚至可能吗?

import java.util.*;
import java.io.*;

public class ExecNoGobble
{
    public static void main(String args[])
    {
        if (args.length < 1)
        {
            System.out.println("USAGE: java ExecNoGobble <cmd>");
            System.exit(1);
        }

        try
        {            
            String[] cmd = new String[3];
                cmd[0] = "cmd.exe" ;
                cmd[1] = "/C" ;
                cmd[2] = args[0];
            Runtime rt = Runtime.getRuntime();
            System.out.println("Execing " + cmd[0] + " " + cmd[1] + " " + cmd[2]);
            Process proc = rt.exec(cmd);
            int exitVal = proc.waitFor();
            System.out.println("ExitValue: " + exitVal);        
        } catch (Throwable t)
          {
            t.printStackTrace();
          }
    }
}

和 ReadInput.java 文件:

import java.io.*;

public class ReadInput {

   public static void main (String[] args) {

      //  prompt the user to enter their name
      System.out.print("Enter your name: ");

      //  open up standard input
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

      String userName = null;

      //  read the username from the command-line; need to use try/catch with the
      //  readLine() method
      try {
         userName = br.readLine();
      } catch (IOException ioe) {
         System.out.println("IO error trying to read your name!");
         System.exit(1);
      }

      System.out.println("Thanks for the name, " + userName);

   }

}  // end of ReadInput class

最后,启动它的批处理文件:

@echo off

echo.
echo Try to run a program  (click a key to continue)
echo.
pause>nul
java ExecNoGobble "java -cp . ReadInput"
echo.
echo (click a key to end)
pause>nul

我还在这里发布了问题: http://forums.oracle.com/forums/message.jspa?messageID=9747449

调用Process.getOutputStream方法并将您的输入提供给返回的 output stream。

api 文档

 public abstract OutputStream getOutputStream()

获取子进程的output stream。 Output 到 stream 被管道输送到此进程所代表的进程的标准输入 stream ZA8CFDE63311C49B66

实施注意事项:最好对 output stream 进行缓冲。

 Returns:

output stream 连接到子进程的正常输入。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM