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

前端 未结 17 1847
长发绾君心
长发绾君心 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:36

    and here is the StreamThread

    public class CommandStreamThread extends Thread{
            private InputStream iStream;
            private String cPrompt;
    
            CommandStreamThread (InputStream is, String cPrompt)
            {
                this.iStream = is;
                this.cPrompt = cPrompt;
            }
    
            public void run()
            {
                try
                {
                    InputStreamReader streamReader= new InputStreamReader(this.iStream);
                    BufferedReader reader = new BufferedReader(streamReader);
    
    
                    String linesep=System.getProperty("line.separator");
                    String line=null;
                    while ((line=reader.readLine())!=null){
                        System.out.println(line);
                        //Process the next line seperately in case this is EOF is not preceded by EOL
                        int in;
                        char[] buffer=new char[linesep.length()];
                        while ( (in = reader.read(buffer)) != -1){
                            String bufferValue=String.valueOf(buffer, 0, in);
                            System.out.print(bufferValue);
                            if (bufferValue.equalsIgnoreCase(linesep))
                                break;
                        }
                    }
    
                    //Or the easy way out with commons utils!
                    //IOUtils.copy(this.iStream, System.out);
    
    
                  } catch (Exception e){
                        e.printStackTrace();  
                  }
            }
    
            public InputStream getIStream() {
                return iStream;
            }
    
            public void setIStream(InputStream stream) {
                iStream = stream;
            }
    
            public String getCPrompt() {
                return cPrompt;
            }
    
            public void setCPrompt(String prompt) {
                cPrompt = prompt;
            }
    
    
    }
    

提交回复
热议问题