简体   繁体   中英

How to get stream output as string?

In my servlet I am running a few command line commands in background, I've successfully printed output on console.

My doGet()

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
{
String[] command =
        {
      "zsh"
          };
                Process p = Runtime.getRuntime().exec(command);
                new Thread(new SyncPipe(p.getErrorStream(), response.getOutputStream())).start();
                new Thread(new SyncPipe(p.getInputStream(), response.getOutputStream())).start();
                PrintWriter stdin = new PrintWriter(p.getOutputStream());
                stdin.println("source ./taxenv/bin/activate");
                stdin.println("python runner.py");
                stdin.close();
                int returnCode = 0;
                try {
                    returnCode = p.waitFor();
                }
                catch (InterruptedException e) {
                    e.printStackTrace();
                } System.out.println("Return code = " + returnCode);
    }               
    class SyncPipe implements Runnable
    {
    public SyncPipe(InputStream istrm, OutputStream ostrm) {
          istrm_ = istrm;
          ostrm_ = ostrm;
      }
      public void run() {
          try
          {
              final byte[] buffer = new byte[1024];
              for (@SuppressWarnings("unused")
            int length = 0; (length = istrm_.read(buffer)) != -1; )
              {
                //  ostrm_.write(buffer, 0, length);
                  ((PrintStream) ostrm_).println();
              }

          }
          catch (Exception e)
          {
              e.printStackTrace();
          }
      }
      private final OutputStream ostrm_;
      private final InputStream istrm_;
    }

Now, I want to save the ostrm_ to a string or list, and use that inside doGet()

How to achieve this?

==============================EDIT============================

Based on answers below, I've edited my code as follows

int length = 0; (length = istrm_.read(buffer)) != -1; )
              {
                 // ostrm_.write(buffer, 0, length);
                  String str = IOUtils.toString(istrm_, "UTF-8");
                  //((PrintStream) ostrm_).println();
                  System.out.println(str);

              }

Now, How do I get the str in runnable class into my doGet()?

You can use Apache Commons IO .

Here is the documentation of IOUtils.toString() from their javadocs

Gets the contents of an InputStream as a String using the specified character encoding. This method buffers the input internally, so there is no need to use a BufferedInputStream.

Parameters: input - the InputStream to read from encoding - the encoding to use, null means platform default Returns: the requested String Throws: NullPointerException - if the input is null IOException - if an I/O error occurs

Example Usage:

String str = IOUtils.toString(yourInputStream, "UTF-8");

You can call something like the following:

(EDIT: added also the client calls)

  public void run() {
      try
      {
         String out = getAsString(istrm_);
         ((PrintStream) ostrm_).println(out);

      } catch (Exception e) {
          e.printStackTrace();
      }
  }

    public static String getAsString(InputStream is) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int cur = -1;
        while((cur = is.read()) != -1 ){
            baos.write(cur);
        }

        return getAsString(baos.toByteArray());
    }

    public static String getAsString(byte[] arr) throws Exception {
        String res = "";

        for(byte b : arr){
            res+=(char)b;
        }

        return res;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM