How do I convert an InputStream to a String in Java?

后端 未结 7 2006
梦毁少年i
梦毁少年i 2020-12-08 15:41

Suppose I have an InputStream that contains text data, and I want to convert this to a String (for example, so I can write the contents of the stre

相关标签:
7条回答
  • 2020-12-08 16:05

    This is my version,

    public static String readString(InputStream inputStream) throws IOException {
    
        ByteArrayOutputStream into = new ByteArrayOutputStream();
        byte[] buf = new byte[4096];
        for (int n; 0 < (n = inputStream.read(buf));) {
            into.write(buf, 0, n);
        }
        into.close();
        return new String(into.toByteArray(), "UTF-8"); // Or whatever encoding
    }
    
    0 讨论(0)
提交回复
热议问题