使用java在Linux中啓動GNOME終端進程並將其輸入和輸出重定向到我的代碼。以下是一個代碼。Java進程IO
public static void main(String[] args) throws InterruptedException
{
// TODO Auto-generated method stub /usr/bin/telnet
try
{
String line, commandInput;
Scanner scan = new Scanner(new File("/home/Ashutosh/Documents/testfile"));
ProcessBuilder telnetProcessBuilder = new ProcessBuilder("/bin/bash");///home/Ashutosh/Documents/tempScript");
telnetProcessBuilder.redirectErrorStream(true);
Process telnetProcess = telnetProcessBuilder.start();
//Process telnetProcess = Runtime.getRuntime().exec("xterm");///home/Ashutosh/Documents/tempScript");
BufferedReader input = new BufferedReader(new InputStreamReader(telnetProcess.getInputStream()));
BufferedWriter output = new BufferedWriter(new OutputStreamWriter(telnetProcess.getOutputStream()));
while(scan.hasNext())
{
commandInput = scan.nextLine();
output.write(commandInput);
/* if(commandInput.trim().equals("exit"))
{
output.write("exit\r");
}
else
{
output.write("((" + commandInput + ") && echo --EOF--) || echo --EOF--\r");
}
*/ output.flush();
line = input.readLine();
while(line != null && !line.trim().equals("--EOF--"))
{
System.out.println(line);
line = input.readLine();
}
if(line == null)
break;
}
/* Thread.sleep(500);
output.write("/home/Ashutosh/Documents/testfile\r");
Thread.sleep(500);
output.flush();
while((line = input.readLine())!= null)
System.out.println(line);
telnetProcess.destroy();
*/ //String s = input.readLine();
//System.out.print(s + "\r\n");
//s = input.readLine();
//System.out.print(s + "\r\n");
}
testfile的內容是bash腳本是
#!/bin/bash
ls -l
pwd
date
exit
,我也嘗試了以下交互式腳本這需要輸入從用戶我想從Java代碼重定向給出
#! /bin/bash
echo "Input any number form 0-3:"
read num
case $num in
0) echo "You are useless";;
1) echo "You are number 1";;
2) echo "Too suspecious";;
3) echo "Thats all man, got to go...!";;
*) echo "Cant't u read english, this is wrong choice";;
esac
read
exit
我的代碼停在input.readLine();
即時通訊不知道,但我認爲我無法重定向輸出流
output.write(commandInput);
命令運行良好,但沒有寫入我打算在進程重定向輸入,這就是爲什麼它掛起在readLine();
。 如果有人已經解決了請讓我知道解決方案。 從下面的鏈接,我試圖解決這個問題,但仍然沒有運氣:
Java Process with Input/Output Stream
感謝
Ashutosh說
喜讀在字符串中讀取命令後添加「\ n」或「\ r」,沒有任何變化,我不知道可能是什麼問題? – Ashutosh 2011-04-27 12:01:19