Search code examples
javainputstreamtelnetapache-commons-net

read open stream till end in java


I am getting a input stream from apache's telnet client.Every time I send a command to telnet client it writes the terminal output back to InputStream,but this stream remains open until the telnet session.

Now I want a way to read the data on this stream till the end.Problem is end can't be determined as the stream is always open.One workaround I found was to read data till a specific character is encountered(which is prompt in most of the cases).but the prompt keeps on changing based on command and I have no way to know what it ll be after command execution.

there is a similar question on SO which explains it better but there is no answer :

Problems with InputStream

Please help...


Solution

  • finally I did using timeout.So basically,I did that ,if character is not available for 1 sec then give up.Instead of inputStream.read() I used this :

    private char readChar(final InputStream in){
            ExecutorService executor = Executors.newFixedThreadPool(1);
            //set the executor thread working
            Callable<Integer> task = new Callable<Integer>() {
                public Integer call() {
                   try {
                       return in.read();
                   } catch (Exception e) {
                      //do nothing
                   }
                   return null;
                }
             };
    
             Future<Integer> future = executor.submit(task);
             Integer result =null;
             try {
                  result= future.get(1, TimeUnit.SECONDS); //timeout of 1 sec
              } catch (TimeoutException ex) {
                  //do nothing
              } catch (InterruptedException e) {
                 // handle the interrupts
              } catch (ExecutionException e) {
                 // handle other exceptions
              } finally {
                  future.cancel(false);
                  executor.shutdownNow();
               }
    
             if(result==null)
                 return (char) -1;
            return  (char) result.intValue();
        }