FileInputStream作用
FileInputStream主要用于读取文件,将文件信息读到内存中。
FileInputStream构造方法
构造方法有三个,常用的有以下两个:
1、FileInputStream(File file),参数传入一个File类型的对象。
2、FileInputStream(String name),参数传入文件的路径。
FileInputStream常用方法
1、int read()方法
从文件的第一个字节开始,read方法每执行一次,就会将一个字节读取,并返回该字节ASCII码,如果读出的数据是空的,即读取的地方是没有数据,则返回-1,如下列代码:
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis=new FileInputStream("a");
//开始读
int readData;
while((readData=fis.read())!=-1) {
System.out.println((char)readData);
}
}catch (IOException e) {
e.printStackTrace();
}finally {
//流是空的时候不能关闭,否则会空指针异常
if(fis!=null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文件a中存储了abcd四个字母,读出结果也是abcd。
2、int read(byte b[])
该方法与int read()方法不一样,该方法将字节一个一个地往byte数组中存放,直到数组满或读完,然后返回读到的字节的数量,如果**一个字节都没有读到,则返回-1。**如下列代码:
public static void main(String[] args) {
FileInputStream fis = null;int readCount;
try {
fis=new FileInputStream("a");
while((readCount=fis.read(b))!=-1) {
System.out.print(new String(b,0,readCount));
}
}catch (IOException e) {
e.printStackTrace();
}finally {
if(fis!=null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
a文件存的是abcde,读出结果是abcde。
(new String(b,0,readCount));是为了将读到的字节输出,如果直接输出b数组,则最后一次只读了de,但数组原来的第三个元素是c,最后输出结果就变成了:abcdec
FileInputStream的其他方法
1、int available();获取文件中还可以读的字节(剩余未读的字节)的数量。
作用:可以直接定义一个文件总字节数量的Byte数组,一次就把文件所有字节读到数组中,就可以不使用循环语句读。 但这种方式不适合大文件,因为数组容量太大会耗费很多内存空间。
2、long skip(long n);将光标跳过n个字节。