Convert Contents Of A ByteArrayInputStream To String

后端 未结 5 1025
盖世英雄少女心
盖世英雄少女心 2020-12-30 23:11

I read this post but I am not following. I have seen this but have not seen a proper example of converting a ByteArrayInputStream to String using

相关标签:
5条回答
  • 2020-12-30 23:33

    A ByteArrayOutputStream can read from any InputStream and at the end yield a byte[].

    However with a ByteArrayInputStream it is simpler:

    int n = in.available();
    byte[] bytes = new byte[n];
    in.read(bytes, 0, n);
    String s = new String(bytes, StandardCharsets.UTF_8); // Or any encoding.
    

    For a ByteArrayInputStream available() yields the total number of bytes.


    Answer to comment: using ByteArrayOutputStream

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buf = new byte[8192];
    for (;;) {
        int nread = in.read(buf, 0, buf.length);
        if (nread <= 0) {
            break;
        }
        baos.write(buf, 0, nread);
    }
    in.close();
    baos.close();
    byte[] bytes = baos.toByteArray();
    

    Here in may be any InputStream.


    Since java 10 there also is a ByteArrayOutputStream#toString(Charset).

    String s = baos.toString(StandardCharsets.UTF_8);
    
    0 讨论(0)
  • 2020-12-30 23:36

    Use Scanner and pass to it's constructor the ByteArrayInputStream then read the data from your Scanner , check this example :

    ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(new byte[] { 65, 80 });
    Scanner scanner = new Scanner(arrayInputStream);
    scanner.useDelimiter("\\Z");//To read all scanner content in one String
    String data = "";
    if (scanner.hasNext())
        data = scanner.next();
    System.out.println(data);
    
    0 讨论(0)
  • 2020-12-30 23:37

    Java 9+ solution:

    new String(inputStream.readAllBytes(), StandardCharsets.UTF_8);
    
    0 讨论(0)
  • 2020-12-30 23:45

    Why nobody mentioned org.apache.commons.io.IOUtils?

    import java.nio.charset.StandardCharsets;
    import org.apache.commons.io.IOUtils;
    
    String result = IOUtils.toString(in, StandardCharsets.UTF_8);
    

    Just one line of code.

    0 讨论(0)
  • 2020-12-30 23:48

    Use Base64 encoding

    Assuming you got your ByteArrayOutputStream :

    ByteArrayOutputStream baos =...
    String s = new String(Base64.Encoder.encode(baos.toByteArray()));
    

    See http://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html

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