我使用 java 在 linux 中启动 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");
}
作为bash脚本的testfile的内容是
#!/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
谢谢
阿舒托什
最佳答案
readLine() 读取一行的内容,末尾没有换行符。
write() 只写入文本,不添加新行。
也许你想添加 write("\n");或使用 PrintStream 或 PrintWriter。
我想,您的脚本发送为
#!/bin/bashls -lpwddateexit
这是没有换行符的注释。
关于Java进程IO,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5803094/