简体   繁体   English

如何获取流输出为字符串?

[英]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. 在我的servlet中,我正在后台运行一些命令行命令,我已经在控制台上成功打印了输出。

My doGet() 我的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() 现在,我想将ostrm_保存到字符串或列表中,并在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()? 现在,如何将可运行类中的str放入doGet()中?

You can use Apache Commons IO . 您可以使用Apache Commons IO

Here is the documentation of IOUtils.toString() from their javadocs 这是IOUtils.toString()的javadoc文档

Gets the contents of an InputStream as a String using the specified character encoding. 使用指定的字符编码将InputStream的内容作为String获取。 This method buffers the input internally, so there is no need to use a BufferedInputStream. 此方法在内部缓冲输入,因此无需使用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 参数:input-要从编码中读取的InputStream-要使用的编码,null表示平台默认值返回:请求的字符串抛出:NullPointerException-如果输入为null IOException-如果发生I / O错误

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;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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