我自己写的
private String recvMessage(InputStream in) {
try {
if (null==in){
return "";
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int packetSize = 1024;
byte[] data = new byte[packetSize];
int len;
while ((len = in.read(data)) != -1) {
baos.write(data, 0, len);
}
baos.flush();
String content= baos.toString();
LogUtil.i("content:" + content);
return content;
} catch (Exception e) {
LogUtil.i("Exception:" + e);
e.printStackTrace();
}
return null;
}
网上的
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
InputStream in = null;
File f = new File("D:/test.txt");
byte[] b = new byte[1024];
in = new FileInputStream(f);
int i = 0;
while ((i = in.read(b)) != -1) {
String str = new String(b);
System.out.print(str);
}
}
网上这个本身没有问题, 这行 String str = new String(b)有问题,因为长度是写死的1024,那么最后一串读出来的数据,不足1024,会补充一些不应该的数据到1024长度。
本文探讨了Java中使用InputStream读取文件时常见的问题,特别是针对最后一块数据不足预设字节数导致的错误读取现象。通过对比自定义方法与网上示例,分析了如何正确地处理不同长度的数据包。
2157

被折叠的 条评论
为什么被折叠?



