FileInputStream 文件字节输入流,常用于从系统上读取数据,以字节的方式。它继承了 InputStream 类,InputStream是字节输入流的抽象类。
FileInputStream 常用的构造方法,它们都抛出一个FileNotFoundException的异常,当文件路径不正确的时候会触发。这个在编码的时候要处理掉,使用自定义异常来处理,不能直接往外抛。
FileInputStream(String name):该方法传入一个字符串类型的参数,要读取文件的绝对路径。
public FileInputStream(String name) throws FileNotFoundException {
this(name != null ? new File(name) : null);
}
示例:
InputStream is = new FileInputStream("e:/app/f.txt");
FileInputStream(File file):该方法传入一个file类型的数据。
public FileInputStream(File file) throws FileNotFoundException {
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(name);
}
if (name == null) {
throw new NullPointerException();
}
fd = new FileDescriptor();
fd.incrementAndGetUseCount();
open(name);
}
示例:
File file = new File("e:/app/f.txt");
InputStream ins = new FileInputStream(file);
FileInputStream 的常用方法,read方法,它有几个重载,int readBytes(byte b[], int off, int len) 是基础,它是native 方法。read(byte b[]) 方法调用了 int readBytes(byte b[], int off, int len) 方法。read方法返回一个-1表示还没有读取结束,常将它的结果3和人-1比较,不等于-1继续读取。
操作完成后要释放资源,掉用 close() 方法,关闭流。
看下面一个例子,该示例使用FileInputStream 读取文件中的内容,并在控制台上打印出来。
该示例中使用了 FileInputStream 的 read(byte [] b) 方法,为了避免浪费内存,该数据的大小根据要读取文件的大小来指定。
package cmc.com.jer.cmc;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class Demo3 {
public static void main(String[] args) {
// 声明 file
File file = new File("e:/app/f.txt");
// 这个数组的大小根据文件来指定,避免内存浪费 ,该数组用来存储读取的字节
byte [] b = new byte[(int)file.length()];
// 字节输入流 FileInputStream
InputStream in =null;
try {
in = new FileInputStream(file);
try {
//把读取到的字节新放入 数组 b中
in.read(b);
System.out.println(new String(b));
} catch (IOException e) {
e.printStackTrace();
} finally {
if(in !=null){
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}