日期:2014-05-18  浏览次数:20751 次

文件读取代码看不懂
package No44;
import java.io.*;
public class No44_6 {

/**
 * 演示FileInputStream类的使用(读文件)
 */
public static void main(String[] args) {
// TODO Auto-generated method stub
File f=new File("d:\\ss.txt");
FileInputStream fis =null;
try {
 fis=new FileInputStream(f);
//定义一个字节数组,相当于缓存
byte bytes[]=new byte[1024];
int n=0;//得到实际读取到的字节数

while((n=fis.read(bytes))!=-1)
{
//把字节转成String
String s=new String(bytes,0,n);
System.out.println(s);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//关闭文件流

}
}

}
代码如上:
byte bytes[]=new byte[1024];
int n=0;//得到实际读取到的字节数
表示缓存,第一次读入1024字节,假如文件超过1024字节,数组如何继续循环读取呢?
byte bytes[]=new byte[1024];
没有在循环体中啊。谢谢

------解决方案--------------------
在这里 大神
while((n=fis.read(bytes))!=-1)
这里的1024字节数应该是根据机器配置来的 可以设置大 也可以设置小
------解决方案--------------------
read
public int read(byte[] b)
         throws IOException从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。在某些输入可用之前,此方法将阻塞。 

覆盖:
类 InputStream 中的 read
参数:
b - 存储读取数据的缓冲区。 
返回:
读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1

也就是说fis.read(bytes)这句吧读出来的数据放入bytes数组里面了。
还有你这里的循环不可能超过1024字节,因为你bytes数组只有这么大,数组里面只读出来这么大的数据

------解决方案--------------------
[color=#FF0000]补充:
while((n=fis.read(bytes))!=-1)
{
//把字节转成String
String s=new String(bytes,0,n);
System.out.println(s);
}
这fis.read(bytes)每次循环放入bytes中的大小就是bytes数组的大小。
比如:第一次读了1024个字节,然后第二次循环又从从数组的[0]开始存入第二次读出的数据,直到全部读取
color]
------解决方案--------------------
while((n=fis.read(bytes))!=-1)
这句话已经将数据放到了循环中。也就是说,每读一次,会重新将文件的下一个1024放到数组中。