How to add a timeout value when using Java's Runtime.exec()?

前端 未结 17 1852
长发绾君心
长发绾君心 2020-11-27 12:08

I have a method I am using to execute a command on the local host. I\'d like to add a timeout parameter to the method so that if the command being called doesn\'t finish in

17条回答
  •  忘掉有多难
    2020-11-27 12:17

    I know this is really old post; i needed some help with a similar project so I thought I might give some of my code that I worked and ones that work.

    long current = System.currentTimeMillis();
    
    ProcessBuilder pb  = new ProcessBuilder(arguments);
    try{
        pb.redirectErrorStream(true);
        process = pb.start();
        int c ;
        while((c = process.getInputStream().read()) != -1 )
            if(System.currentTimeMillis() - current < timeOutMilli) 
                result += (char)c;
            else throw new Exception();
        return result.trim();
        }catch(Exception e){
            e.printStackTrace();
        }
        return result;
    

    Hope this helps the future :D

提交回复
热议问题