linux Java进程IO
我在linux中使用java启动GNOME终端进程,并将其输入和输出重定向到我的代码。下面是一个代码
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);
命令执行得很好,但没有在进程重定向输入上写入我想要的内容,这就是它挂起的原因。 如果有人已经解决了,请告诉我解决方案。 通过以下链接,我试图解决这个问题,但仍然没有成功:
Java Process with Input/Output Stream
谢谢
阿什图什
共 (0) 个答案