Java Process IO

时间:2011-04-27 11:11:14

标签: java linux

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

由于

Ashutosh说

3 个答案:

答案 0 :(得分:2)

readLine()读取一行的内容,最后没有换行符。

write()只写文本,不添加新行。

也许你想添加写(“\ n”);或使用PrintStream或PrintWriter。

我想,您的脚本将作为

发送
#!/bin/bashls -lpwddateexit

这是没有换行符的评论。

答案 1 :(得分:1)

编辑:巨大的错误,没有将命令添加到ProcessBuilder !!

为什么不只是将脚本作为Linux脚本运行?也就是说,

ProcessBuilder builder = new ProcessBuilder();
LinkedList<String> command = new LinkedList<String>();
command.add("/bin/bash");
command.add("/home/Ashutosh/Documents/testfile");
builder.command(command);

Process myProc = builder.start();

另外,我注意到该变量名为'telnetProcess',但我无法在任何地方调用telnet。也许这就是问题?

编辑:在下面添加了我对交互式脚本的建议。

ProcessBuilder builder = new ProcessBuilder();
LinkedList<String> command = new LinkedList<String>();
command.add("/bin/bash");
command.add("/path/to/interactiveScript");
builder.command(command);

final Process myProc = builder.start();

// Java input goes to process input.
Thread inputParser = new Thread() {
  public void run() {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(myProc.getOutputStream()));
    String line = "";
    while(line != null) {
      line = br.readLine();
      bw.write(line);
      bw.newLine();
    }
  }
}.start();

// Process output must go to Java output so user can see it!
Thread outputParser = new Thread() {
  public void run() {  
    BufferedReader br = new BufferedReader(new InputStreamReader(myProc.getInputStream()));
    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    String line = "";
    while(line != null) {
      line = br.readLine();
      bw.write(line);
      bw.newLine();
    }
  }
}.start();

答案 2 :(得分:1)

嗨,大家好抱歉迟到的回复,经过一些试验,我得到了它的工作。我只是让进程完成其进程并正常退出而不是强行退出然后BufferedReader和BufferedWriter将字符串缓冲区保存在RAM中,我现在可以在进程退出后用代码0读取。

public static void main(String[] args) throws InterruptedException
{
    // TODO Auto-generated method stub
    try
    {
        String line, commandInput;
        ProcessBuilder telnetProcessBuilder = new ProcessBuilder("/bin/bash");
        telnetProcessBuilder.redirectErrorStream(true);
        Process telnetProcess = telnetProcessBuilder.start();
        BufferedReader input = new BufferedReader(new InputStreamReader(telnetProcess.getInputStream()));
        BufferedWriter output = new BufferedWriter(new OutputStreamWriter(telnetProcess.getOutputStream()));
        commandInput = "ls -l\n";
        output.write(commandInput);
        output.flush();
        commandInput = "pwd\n";
        output.write(commandInput);
        output.flush();
        commandInput = "whoami\n";
        output.write(commandInput);
        output.flush();
        commandInput = "exit\n";
        output.write(commandInput);
        output.flush();
        while((line = input.readLine())!= null)
            System.out.println(line);
    }
}