需求是讀取流轉(zhuǎn)為String
原本方法
InputStream is;
byte[] data = new byte[is.available()];
is.read(data);
String str= new String(data);
出現(xiàn)問(wèn)題:流轉(zhuǎn)換不全,部分信息丟失
出現(xiàn)原因:癥結(jié)在于available()方法,該方法是獲取流大小,對(duì)本地文件沒(méi)有問(wèn)題世蔗。但是網(wǎng)絡(luò)傳輸中文件較大可能會(huì)分批次傳輸,所以此時(shí)available()不能獲取總長(zhǎng)度朗兵。
改進(jìn)方法
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());
改為循環(huán)讀取
本地測(cè)試
public static void main(String[] args) throws Exception {
// 測(cè)試一次性讀取與循環(huán)讀取
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());
}
對(duì)于本地文件污淋,兩種方法打印字符串長(zhǎng)度一致
線上測(cè)試,本地發(fā)起一個(gè)請(qǐng)求余掖,打印參數(shù)大小寸爆,接收端打印available大小,這時(shí)候就不一致了盐欺。
參數(shù):
接收:
參考文章
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