【问题标题】:Get bytedata data in string获取字符串中的字节数据数据
【发布时间】:2015-03-30 15:24:10
【问题描述】:
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); 之前我想把每一行(从输入文本中读取)文件变成一个字符串。是否可以把这个字节数据变成一个字符串。

【问题讨论】:

    标签: java string byte fileinputstream fileoutputstream


    【解决方案1】:

    更好的方法是使用proper String constructor:

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

    这样可以避免不必要的数组复制。

    此外,如果数据编码可能与您平台的默认编码不同,您必须使用a constructor,它将Charset 作为附加参数。

    【讨论】:

      【解决方案2】:

      简单地说:

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

      或者使用不使用默认字符集的字符集:

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

      【讨论】:

      • 做到了。我有时真的很愚蠢。那件事从来没有出现在我的脑海中。再次非常感谢
      • 当然,我不知道这个构造函数。
      猜你喜欢
      • 2020-01-11
      • 2021-07-31
      • 1970-01-01
      • 2015-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-31
      • 2018-08-16
      相关资源
      最近更新 更多