我自己写的 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长度。