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

后端 未结 7 2013
梦毁少年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:04

    You can use a BufferedReader to read the stream into a StringBuilder in a loop, and then get the full contents from the StringBuilder:

    public String convertStreamToString(InputStream is) { 
      BufferedReader reader = new BufferedReader(new InputStreamReader(is)); 
      StringBuilder sb = new StringBuilder(); 
    
      String line = null; 
    
      try { 
        while ((line = reader.readLine()) != null) { 
        sb.append(line + "\n"); 
        } 
      } catch (IOException e) { 
        e.printStackTrace(); 
      } finally { 
        try { 
          is.close(); 
        } catch (IOException e) { 
          e.printStackTrace(); 
        } 
      }
    
      return sb.toString(); 
    } 
    

    Full disclosure: This is a solution I found on KodeJava.org. I am posting it here for comments and critique.

提交回复
热议问题