FileInputStream 用于读取本地文件中的字节数据,继承自InputStream类
构造方法摘要
FileInputStream(File file)
通过打开一个到实际文件的连接来创建一个FileInputStream,该文件通过文件系统中的 File 对象 file 指定。
FileInputStream(FileDescriptor fdObj)
通过使用文件描述符 fdObj 创建一个FileInputStream,该文件描述符表示到文件系统中某个实际文件的现有连接。
FileInputStream(String name)
通过打开一个到实际文件的连接来创建一个FileInputStream,该文件通过文件系统中的路径名 name 指定。
方法摘要
int available()
返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取(或跳过)的估计剩余字节数。
void close()
关闭此文件输入流并释放与此流有关的所有系统资源。
protected void finalize()
确保在不再引用文件输入流时调用其close 方法。
FileChannel getChannel()
返回与此文件输入流有关的唯一FileChannel 对象。
FileDescriptor getFD()
返回表示到文件系统中实际文件的连接的 FileDescriptor 对象,该文件系统正被此FileInputStream 使用。
int read()
从此输入流中读取一个数据字节。
int read(byte[] b)
从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。
int read(byte[] b, int off, int len)
从此输入流中将最多 len 个字节的数据读入一个 byte 数组中。
long skip(long n)
从输入流中跳过并丢弃 n 个字节的数据。
其中read()返回的是读入的一个字节所对应的int值(0-255),而read(byte[] b) 和read(byte[] b, int off, int len) 返回的是读入的字节数
代码实例
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputDemo {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("D:\\java\\theTestOnClass\\src\\com\\qst\\IO\\FileInputDemo.java");
byte[] b = new byte[5];
// 方法一: int read(byte[] b)
/* try {
while((fis.read(b)) != -1){
System.out.print(new String(b));
b = new byte[5];
}
} catch (IOException e) {
e.printStackTrace();
}*/
// 方法二 int read(byte[] b, int off, int len)
/*
try {
while((fis.read(b, 0, b.length)) != -1){
System.out.print(new String(b));
}
} catch (IOException e) {
e.printStackTrace();
}
*/
//方法三:int read()
int c = 0;
try {
while((c = fis.read()) != -1){
System.out.print((char) c);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件不存在!");
}
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}