使用缓存字节数组读取java字节流时,第一次读取是,读满缓存字节数组大小,才进行下次读取,还是随机读一个小于数组大小的值,再进行下次读取???
读取本地文件时,首次读取读满整个字节数组,在进行下次读取。
package com.lyf.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
public class ReadFile {
@Test
public void readTxt() {
InputStream is = null;
String path = this.getClass().getClassLoader().getResource("abc.txt")
.getPath();
System.out.println(path);
String content = "";
String loopContentString ="";
try {
is = new FileInputStream(path);
byte buff[] = new byte[16];
int len = is.read(buff);
content = new String(buff, 0, len);
System.out.println(len);
while (len != -1) {
len = is.read(buff);
System.out.println(len);
if(len != -1){
content += new String(buff,0,len);
}
}
System.out.println(content);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
结果:其中abc.txt 大小就26个字节
读取远程数据接口数据流时,
String queryUrl = "/chaxun?com=yuantong&nu=887240223128139035";
try {
URL url = new URL(queryUrl);
URLConnection con = url.openConnection();
con.setAllowUserInteraction(false);
urlStream= url.openStream();
String type = con.guessContentTypeFromStream(urlStream);
String charSet = null;
if (type == null){
type = con.getContentType();
}
if (type == null || type.trim().length() == 0
|| type.trim().indexOf("text/html") < 0){
return;
}
if (type.indexOf("charset=") > 0){
charSet = type.substring(type.indexOf("charset=") + 8);
}
byte b[] = new byte[100];
int numRead = urlStream.read(b);
String content = new String(b, 0, numRead);
System.out.println("b中的内容用ascii表示,第3个字符的码是="+b[2]+"||第一次:"+numRead+"||"+content);
int i = 0;
while (numRead != -1) {
numRead = urlStream.read(b);
if (numRead != -1) {
i++;
// String newContent = new String(b, 0, numRead);
String newContent = new String(b, 0, numRead, charSet);
System.out.println("第"+i+"次:"+numRead+"||"+newContent);
content += newContent;
}
}
System.out.println(content);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
urlStream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
读取结果:远程数据流的大小2032个字节
第一次读取只读了,27个字节,
问题:为啥读取本地文件和远程数据的首次读取不同,是网络问题,还是java中read函数的限制??
纳闷............
java读取字节流设置字节数组长度_java读取流数据时 字节缓存数组 第一次读取时 是否读满 才进行下次读取??...