Read text from InputStream

This question already has an answer here:

  • Read/convert an InputStream to a String 56 answers

  • 取决于您所熟悉的许可证,这是雅加达共享IO库的一个班轮。


    Do specify the character encoding. Do not waste code, introduce bugs, and slow execution with a BufferedReader .

    Here is an example. You could parameterize it with a buffer size, encoding, etc.

    static String readString(InputStream is) throws IOException {
      char[] buf = new char[2048];
      Reader r = new InputStreamReader(is, "UTF-8");
      StringBuilder s = new StringBuilder();
      while (true) {
        int n = r.read(buf);
        if (n < 0)
          break;
        s.append(buf, 0, n);
      }
      return s.toString();
    }
    

    Using Commons-IO is likely to be the best option. For your interest, another approach is to copy all the bytes and then convert it into a String.

    public static String readText(InputStream is, String charset) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes = new byte[4096];
        for(int len;(len = is.read(bytes))>0;)
            baos.write(bytes, 0, len);
        return new String(baos.toByteArray(), charset);
    }
    
    链接地址: http://www.djcxy.com/p/13726.html

    上一篇: 来自InputStream的Java字符串

    下一篇: 从InputStream中读取文本