Java中FileInputStream类的常用方法

FileInputStream类

从文件系统中的某个文件中获得输入字节。(继承自InputStream类)

构造方法

public FileInputStream(File file)
通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的 File 对象 file 指定。

public FileInputStream(String name)
通过打开一个到实际文件的连接来创建一个 FileInputStream,该文件通过文件系统中的路径名 name 指定。

常用方法

public abstract int read() throws IOException:
一次读取一个字节
返回:下一个数据字节;如果已到达文件末尾,则返回 -1。

public int read(byte[] b) throws IOException:
一次读取一个字节数组 (读取实际的字节数)     指定字节数组的长度是:1024或者1024的倍数
返回:读入缓冲区的字节总数,如果因为已经到达文件末尾而没有更多的数据,则返回 -1。
b - 存储读取数据的缓冲区

开发步骤:

 1)创建字节文件输入流对象
 2)读数据
 3)释放资源

示例程序:

public class FileInputStreamDemo {
    public void demo() throws Exception{
                FileInputStream fis  = new FileInputStream("fis.txt") ;
        int by = 0 ;
        while((by=fis.read())!=-1) {
            System.out.print((char)by);
        }        
        //释放资源
        fis.close();       
    }
}


猜你喜欢

转载自blog.csdn.net/scbiaosdo/article/details/80351413