我遇到了一个问题,当使用Java Runtime运行另一个java程序时,程序冻结,因为其他程序需要stdin。使用Runtime exec()执行另一个java程序后,处理stdin时出现问题。
以下是我无法工作的示例代码。这甚至可能吗?
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
答案 0 :(得分:3)
调用方法Process.getOutputStream
并将输入提供给返回的输出流。
public abstract OutputStream getOutputStream()
获取子进程的输出流。输出到流是 用管道传输到表示的过程的标准输入流 这个Process对象。
实施说明:输出流是个好主意 缓冲。
Returns:
输出流连接到的正常输入 子进程。