使用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