写入Java进程的InputStream

我有一个代码,通过启动一个Java过程(即:执行一个编译的Java代码)

ProcessBuilder builder = new ProcessBuilder("java", "Sample", "arg1", "arg2"); builder.redirectErrorStream(true); Process process = builder.start(); 

通过这个,我基本上可以处理输出和错误

 OutputStream stdin = process.getOutputStream(); // <- Eh? InputStream stdout = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stdout)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin)); // reader.readLine() blah blah 

现在,我怎样才能发送input到stdin ? 也就是说,如果进程执行的代码有一个等待input的行,如下所示:

 Scanner scan = new Scanner(System.in); String val = scan.nextLine(); System.out.println(val); 

我试过这个:

 writer.write("I'm from the stdin!."); writer.flush(); 

虽然没有发生。 控制台仍在等待input。

有什么想法吗?

编辑:这个问题被回答,如下所接受。 我正在编辑,以显示错误的代码 (我没有包括顺便说一句,大声笑)。

writer.write()之前,我有一个

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

Process OuputStream (我们的观点)是从进程angular度来看STDIN

 OutputStream stdin = process.getOutputStream(); // write to this 

所以你有什么应该是正确的。

我的驱动程序(没有适当的streampipe理)

 public class ProcessWriter { public static void main(String[] args) throws Exception { ProcessBuilder builder = new ProcessBuilder("java", "Test"); builder.directory(new File("C:\\Users\\sotirios.delimanolis\\Downloads")); Process process = builder.start(); OutputStream stdin = process.getOutputStream(); // <- Eh? InputStream stdout = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(stdout)); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin)); writer.write("Sup buddy"); writer.flush(); writer.close(); Scanner scanner = new Scanner(stdout); while (scanner.hasNextLine()) { System.out.println(scanner.nextLine()); } } } 

我的应用程序

 public class Test { public static void main(String[] args) throws Exception { Scanner console = new Scanner(System.in); System.out.println("heello World"); while(console.hasNextLine()) { System.out.println(console.nextLine()); } } } 

运行驱动程序打印

 heello World Sup buddy 

出于某种原因,我需要close()flush()本身不会。

编辑它也可以工作,而不是close()你提供一个\n

所以

 writer.write("Sup buddy"); writer.write("\n"); writer.write("this is more\n"); writer.flush(); 

司机打印

 heello World Sup buddy this is more