第一个构造方法
public FileInputStream(File file)throws FileNotFoundException
public class Test12 {
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test.txt");
InputStream in=new FileInputStream(f);
byte[] b=new byte[1024];
int len=in.read(b);
in.close();
System.out.println(new String(b,0,len));
}
}
但以上方法是有问题的,用不用开辟这么大的一个字节数组,明显是浪费嘛,我们可以根据文件的大小来定义字节数组的大小,File类中的方法:public long length()
public class Test13 {
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test.txt");
InputStream in=new FileInputStream(f);
byte[] b=new byte[(int) f.length()];
in.read(b);
in.close();
System.out.println(new String(b));
}
}
我们换种方式,一个字节一个字节读入~
public class Test14 {
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test.txt");
InputStream in=new FileInputStream(f);
byte[] b=new byte[(int) f.length()];
for(int i=0;i<b.length;i++){
b[i]=(byte) in.read();
}
in.close();
System.out.println(new String(b));
}
}
但以上情况只适合知道输入文件的大小,不知道的话用如下方法:
public class Test15 {
public static void main(String[] args) throws IOException {
File f = new File("d:" + File.separator+"test.txt");
InputStream in=new FileInputStream(f);
byte[] b=new byte[1024];
int temp=0;
int len=0;
while((temp=in.read())!=-1){//-1为文件读完的标志
b[len]=(byte) temp;
len++;
}
in.close();
System.out.println(new String(b,0,len));
}
}