Search code examples
javaiojsch

Entering data into an InputStream


I know that InputStreams are for reading, and OutputStreams are for writing... but if I have an application that passes all data from an InputStream to the remote side and pushes all received data from that remote side to the OutputStream and I need to send dynamic data to that remote side... how would I enter it into the InputStream? I can do this easily in the Java console since anything entered in is put into System.in and sent to that remote side, and anything coming back is processed through System.out, but obviously I cannot use a Java console in production. How would I emulate this functionality e.g. create a button that sends "command X\r" as if it were typed into the java console?

Note: For background, I'm using JSch to SSH into a Cisco ASA. Where I have set Channel.setInputStream(System.in) and Channel.setOutputStream(System.out) to communicate through console successfully.


Solution

  • I am not familiar with JSch, and I suspect you have this backwards. First, according to their example, you should actually be executing commands with Channel.setCommand(). Then you can use Channel.getInputStream() to obtain a stream that you can read the remote response from.

    That aside, a cursory glance at the documentation seems to suggest that you should use the channel's existing streams and read to / write from them, e.g.:

    OutputStream out = Channel.getOutputStream();
    
    String str = "command X\r";
    out.write(str.getBytes("us-ascii"));
    

    This would make more sense and is much easier to deal with on your end.

    However, as to the general question regarding InputStreams: You can use any InputStream as a source for data. It just so happens that System.in is one that comes from standard input (which is essentially a file).

    If you want to use data constructed on the fly, you could use a ByteArrayInputStream, e.g.:

    String str = "command X\r";
    InputStream in = new ByteArrayInputStream(str.getBytes("us-ascii"));
    
    // do stuff with in
    

    You can use any character encoding you want if us-ascii is not appropriate.

    But, again, I suspect you are doing this slightly backwards.