需求是读取流转为String
原本方法
InputStream is;
byte[] data = new byte[is.available()];
is.read(data);
String str= new String(data);
出现问题:流转换不全,部分信息丢失
出现原因:症结在于available()方法,该方法是获取流大小,对本地文件没有问题。但是网络传输中文件较大可能会分批次传输,所以此时available()不能获取总长度。
改进方法
InputStream is;
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
String str = result.toString(StandardCharsets.UTF_8.name());
改为循环读取
本地测试
public static void main(String[] args) throws Exception {
// 测试一次性读取与循环读取
InputStream is = new FileInputStream("D:\\1.txt");
byte[] data = new byte[is.available()];
is.read(data);
String str1 = new String(data);
System.out.println(str1.length());
InputStream is2 = new FileInputStream("D:\\1.txt");
ByteArrayOutputStream result = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = is2.read(buffer)) != -1) {
result.write(buffer, 0, length);
}
String str2 = result.toString(StandardCharsets.UTF_8.name());
System.out.println(str2.length());
}
对于本地文件,两种方法打印字符串长度一致
线上测试,本地发起一个请求,打印参数大小,接收端打印available大小,这时候就不一致了。
参数:
image.png
接收:
image.png
参考文章
https://www.cnblogs.com/javajetty/p/10684957.html
https://blog.csdn.net/qq_34899538/article/details/80277218
https://blog.csdn.net/chengxie3620/article/details/100786792