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

后端 未结 7 2005
梦毁少年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 15:46

    A nice way to do this is using Apache commons IOUtils

    IOUtils.toString(inputStream, string);
    
    0 讨论(0)
  • 2020-12-08 15:52

    Below code might help you.

    public String convertBytestoString(InputStream inputStream)
    {
        int bytes;
        byte[] buffer = new byte[1024];
    
        bytes = inputStream.read(buffer);
        String stringData = new String(buffer,0,bytes);
    
        return stringData;
    
    }
    
    0 讨论(0)
  • 2020-12-08 15:53
    String text = new Scanner(inputStream).useDelimiter("\\A").next();
    

    The only tricky is to remember the regex \A, which matches the beginning of input. This effectively tells Scanner to tokenize the entire stream, from beginning to (illogical) next beginning...
    - from the Oracle Blog

    0 讨论(0)
  • 2020-12-08 15:54

    With Java 9+ even shorter:

    static String readString(InputStream inputStream) throws IOException {
       return new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); // Or whatever encoding
    }
    

    Note: InputStream is not closed in this example.

    0 讨论(0)
  • 2020-12-08 16:01

    If you want to do it simply and reliably, I suggest using the Apache Jakarta Commons IO library IOUtils.toString(java.io.InputStream, java.lang.String) method.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题