以字符串形式获取bytedata数据

时间:2015-03-30 15:24:10

标签: java string byte fileinputstream fileoutputstream

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;
}

在outStream.write之前(buf,0,cntRead);我希望将每一行(从输入文本中读取)文件转换为字符串。是否可以将此字节数据转换为字符串。

2 个答案:

答案 0 :(得分:2)

更好的方法是使用proper String constructor

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

这样可以避免不必要的数组副本。

如果数据编码可能与您平台的默认编码不同,则必须使用a constructor,其中Charset作为附加参数。< / p>

答案 1 :(得分:0)

简单地:

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

或者使用charset不使用默认值:

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