Search code examples
javastringbytefileinputstreamfileoutputstream

Get bytedata data in string


private static int readAndWriteInputStream( final InputStream is, final OutputStream outStream ) throws IOException {
    final byte[] buf = new byte[ 8192 ];
    int read = 0;
    int cntRead;
    while ( ( cntRead = is.read( buf, 0, buf.length ) ) >=0  )
    {
        outStream.write(buf, 0, cntRead);
        read += cntRead;
    }
    outStream.write("\n".getBytes());
    return read;
}

Before outStream.write(buf, 0, cntRead); i want to get every single line(read from input text) file into a String .Is it possible to get this byte data into a string.


Solution

  • Simply:

    String s = new String(buf, 0, cntRead);
    

    Or with a charset not to use the default one:

    String s = new String(buf, 0, cntRead, Charset.forName("UTF-8"));