Run external program concurrently and communicate with it through stdin / stdout

后端 未结 5 1811
耶瑟儿~
耶瑟儿~ 2020-12-06 07:17

I want to be able to run an external program concurrently with my Java code, i.e. I want to start the program, then return control to the calling method while keeping the ex

5条回答
  •  情话喂你
    2020-12-06 08:02

    Have a look at ProcessBuilder. Once you've set up the ProcessBuilder and executed start you'll have a handle to a Process to which you can feed input and read output.

    Here's a snippet to get you started:

    ProcessBuilder pb = new ProcessBuilder("/bin/bash");
    Process proc = pb.start();
    
    // Start reading from the program
    final Scanner in = new Scanner(proc.getInputStream());
    new Thread() {
        public void run() {
            while (in.hasNextLine())
                System.out.println(in.nextLine());
        }
    }.start();
    
    // Write a few commands to the program.
    PrintWriter out = new PrintWriter(proc.getOutputStream());
    out.println("touch hello1");
    out.flush();
    
    out.println("touch hello2");
    out.flush();
    
    out.println("ls -la hel*");
    out.flush();
    
    out.close();
    

    Output:

    -rw-r--r-- 1 aioobe aioobe 0 2011-04-08 08:29 hello1
    -rw-r--r-- 1 aioobe aioobe 0 2011-04-08 08:29 hello2
    

提交回复
热议问题