有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何获得字符串形式的流输出?

在我的servlet中,我在后台运行了一些命令行命令,我已经成功地在控制台上打印了输出

我的狗

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

现在,我想将ostrm_保存到字符串或列表中,并在doGet()中使用它

如何做到这一点

========================================编辑============================

根据下面的答案,我将代码编辑如下

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

              }

现在,如何将runnable类中的str放入我的doGet()中


共 (2) 个答案

  1. # 1 楼答案

    你可以使用Apache Commons IO

    以下是来自他们的Javadoc的IOUtils.toString()文档

    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

    用法示例:

    String str = IOUtils.toString(yourInputStream, "UTF-8");
    
  2. # 2 楼答案

    你可以这样称呼:

    (编辑:还添加了客户端呼叫)

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