java byte[]有效数据长度转String

在java中,在读取文件内容时,通过需要定义个byte[] 数组,把文件内容读取到数组中:

byte[] buffer = new byte[512]; 
FileInputStream fileInputStream = new FileInputStream(file);
int length = fileInputStream.read(buffer);

当把byte[]数组中的数据转换成String字符串时,可以使用以下几种方法:

1.直接使用new关键字来创建字符串,这种方式创建的字符串会引入buffer中无效的数据,通过打印内容时会显示非法内容。


String str = new String(buffer);

 2.使用byte[]数组中的有效数据创建字符串,这种方式生成的字符串只包含有效的数据,推荐使用这种:

String str = new String(buffer, 0, length);
发布了17 篇原创文章 · 获赞 2 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/toove/article/details/99441507