请教前辈:
这是关于文件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);
}
解决方案 »
- 求证一下 primitive type 都有继承Object的语意吗?
- java web 项目中想在持久层把文件写到项目目录下,但是如何获取项目路径?
- 帮忙看看这个程序错在哪
- stat.execute("CREATE DATABASE TEST"); 这句的异常怎么捕捉?
- 用Integer.parseInt()转换字符时抛出NumberFormatException异常,把字符改短一点又没事
- 我刚刚下了一个JSDK1.5.0安装后结果没办打开,怎么办???
- 各位高手进来看看。关于运行JAVA程序的简单问题.
- 请各位给我们这些菜鸟 指一条路!
- xp下如何运行带有java包的程序
- 怎样把byte[]的内容置空 急!急!
- 这个String str为什么没变??
- Json格式的数据怎么转换成List?
执行之后,就读取了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);