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);我希望将每一行(从输入文本中读取)文件转换为字符串。是否可以将此字节数据转换为字符串。
答案 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"));