How can I unblock from a Java started process?

前端 未结 8 1066
旧巷少年郎
旧巷少年郎 2021-01-29 01:27

When executing some command(let\'s say \'x\') from cmd line, I get the following message: \"....Press any key to continue . . .\". So it waits for user input to unblock.

相关标签:
8条回答
  • 2021-01-29 02:18

    Use a PrintWriter to simulate some input:

            Process p = Runtime.getRuntime().exec(cmd, null, cmdDir);
            //consume the proces's input stream
            ........
            // deblock
            OutputStream outputStream = p.getOutputStream();
            PrintWriter pw = new PrintWriter(outputStream);
            pw.write("ok");
            pw.flush();
            int errCode = p.waitFor();
    
    0 讨论(0)
  • 2021-01-29 02:19

    I think the recommended ray of executing external applications in Java is using a ProcessBuilder. The code looks like

    //Launch the program
    ArrayList<String> command = new ArrayList<String>();
    command.add(_program);
    command.add(param1);
    ...
    command.add(param1);
    
    ProcessBuilder builder = new ProcessBuilder(command);
    //Redirect error stream to output stream
    builder.redirectErrorStream(true);
    
    Process process = null;
    BufferedReader br = null;
    try{
        process = builder.start();
    
        InputStream is = process.getInputStream();
        br = new BufferedReader( new InputStreamReader(is));
        String line;
    
        while ((line = br.readLine()) != null) {
             log.add(line);
        }
    }catch (IOException e){
        e.printStackTrace();
    }finally{
        try{
            br.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    

    The process object has a get[Input/Output/Error]Stream that could be used to interact with the program.

    0 讨论(0)
提交回复
热议问题