[英]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。
public abstract OutputStream getOutputStream()
獲取子進程的output stream。 Output 到 stream 被管道輸送到此進程所代表的進程的標准輸入 stream ZA8CFDE63311C49B66
實施注意事項:最好對 output stream 進行緩沖。
Returns:
output stream 連接到子進程的正常輸入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.