Execute a shell command using processBuilder and interact with it

六眼飞鱼酱① 提交于 2019-11-30 23:05:26

"(actually it's "ls" but it should work exactly the same way)"

No, it is not. Because the 'ls' process returns immediately after its call. Your omixplayer at the other hand is interactive and will accept commands at runtime.

What you have to do:

  • create a class which implements Runnable and let this class read from the prs.getInputStream(). You will need this because the .read() will block and wait for new data to read.

  • get the OutputStream of the Process object (prs.getOutputStream()). Everything you write to the OutputStream will be read from your omixplayer. Don't forget to flush the OutputStream and every command needs an "\n" at the end to be executed.

Like that:

public class TestMain {
    public static void main(String a[]) throws InterruptedException {

        List<String> commands = new ArrayList<String>();
        commands.add("telnet");
        commands.add("www.google.com");
        commands.add("80");
        ProcessBuilder pb = new ProcessBuilder(commands);
        pb.redirectErrorStream(true);
        try {

            Process prs = pb.start();
            Thread inThread = new Thread(new In(prs.getInputStream()));
            inThread.start();
            Thread.sleep(2000);
            OutputStream writeTo = prs.getOutputStream();
            writeTo.write("oops\n".getBytes());
            writeTo.flush();
            writeTo.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class In implements Runnable {
    private InputStream is;

    public In(InputStream is) {
        this.is = is;
    }

    @Override
    public void run() {
        byte[] b = new byte[1024];
        int size = 0;
        try {
            while ((size = is.read(b)) != -1) {
                System.err.println(new String(b));
            }
            is.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}

P.S.: Keep in mind this example is quick an dirty.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!