请教前辈:
这是关于文件IO读取的一段代码,代码本身没有错误,现在我感到疑惑的是:
为什么加了此句System.out.println("Total read bytes:"+fis.read(bytes));循环体内的内容不读取,注释此条语句则可以读取文件内的全部内容,难道fis.read(bytes)取这个值后,n就等于-1了吗?
FileInputStream fis=null;
try {
fis=new FileInputStream(f);//定义一个字节数组,逐块读入至内存缓冲区中,
byte[] bytes=new byte[1024];
int n=0;//实际读取的字节数System.out.println("Total read bytes:"+fis.read(bytes));
//-1表示文件已读完
while((n=fis.read(bytes))!=-1){
//将字节转换成字符串
String str=new String(bytes,0,n);
System.out.println(str);
}
这是关于文件IO读取的一段代码,代码本身没有错误,现在我感到疑惑的是:
为什么加了此句System.out.println("Total read bytes:"+fis.read(bytes));循环体内的内容不读取,注释此条语句则可以读取文件内的全部内容,难道fis.read(bytes)取这个值后,n就等于-1了吗?
FileInputStream fis=null;
try {
fis=new FileInputStream(f);//定义一个字节数组,逐块读入至内存缓冲区中,
byte[] bytes=new byte[1024];
int n=0;//实际读取的字节数System.out.println("Total read bytes:"+fis.read(bytes));
//-1表示文件已读完
while((n=fis.read(bytes))!=-1){
//将字节转换成字符串
String str=new String(bytes,0,n);
System.out.println(str);
}
执行之后,就读取了bytes大小的内容,剩下的就不是完整的内容了
稍微改一下:FileInputStream fis=null;
try
{
fis=new FileInputStream(f);
//定义一个字节数组,逐块读入至内存缓冲区中,
byte[] bytes=new byte[1024];
int n=0;//实际读取的字节数 //System.out.println("Total read bytes:"+fis.read(bytes));//--------------这不输出
//-1表示文件已读完
while((n=fis.read(bytes))!=-1)
{
//将字节转换成字符串
System.out.println("Total read bytes:"+n);//--------------这输出读入的大小。
String str=new String(bytes,0,n);
System.out.println(str);
}
你要是想计算一共读了多少字节,就得定义一个变量,然后在循环里做累加。
FileInputStream fis=null;
try {
fis=new FileInputStream(f);//定义一个字节数组,逐块读入至内存缓冲区中,
byte[] bytes=new byte[1024];
int n=0;//实际读取的字节数
int sum=0;//累计读取字节数
//System.out.println("Total read bytes:"+fis.read(bytes));
//-1表示文件已读完
while((n=fis.read(bytes))!=-1){
//将字节转换成字符串
sum+=n;
String str=new String(bytes,0,n);
System.out.println(str);
}
System.out.println("Total read bytes:"+sum);