package text6;
impor java.io.*;
public class Demo11_3 {
public static void main(String[] args) {
File f=new File("f:/bb.txt");
FileInputStream fis=null;
try {
//因为File没有读写的能力,所以需要使用InputStream
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();
}
}
}
这样读取不了 而把!=-1改成==1就能读取这是为什么,视频上相反了啊。本人初学java求大神指导
while((n=fis.read(bytes))!=-1); 能告诉我这个分号肿么回事吗??我日,让我瞅了好久
while((n=fis.read(bytes))!=-1);
{
//把字节转成String
String s=new String(bytes,0,n);//如果读到文件末尾n=-1,bytes数组长度没有-1,越界
System.out.println(s);
}
改成
while((n=fis.read(bytes))!=-1);
{
//把字节转成String
String s=new String(bytes);
System.out.println(s);
}
int n=0;去掉赋值
把读取的代码改成下面这样
int n = fis.read(bytes);
while(n != -1);
{
//把字节转成String
String s=new String(bytes,0,n);
System.out.println(s);
n = fis.read(bytes);
}
想成为一名优秀的程序员,一定要细心哦~不然就连一个小小的分号也能耗上你一天!我也常遇到这种情况~嘻嘻~~~~