I/O输入流基础之FileInputStream

时间:2023-03-09 20:08:13
I/O输入流基础之FileInputStream

InputStream:是所有字节输入流的父类,其作用是:用这个流把网络数据(getOutputStream()),文件系统的数据读入内存

由与  public abstract class InputStream implements Closeable, Flushable{},所以此类不可以直接实例化,只能实例化它的子类:ByteArrayInputStream, FileInputStream, FilterInputStream, ObjectInputStream, PipedInputStream, SequenceInputStream, StringBufferInputStream等.

故对InputStream的操作实际是对其直接子类或者间接子类的操作

以FileInputStream为例:class FileInputStreamextends InputStream{.....}

构造描述:输入流对象的创建

   public FileInputStream(File file):  创建一个指向文件的输入流,即将该文件内容读到内存中

   public FileInputStream(String name) : 创建一个指向文件的输入流,即将该文件内容读到内存中

  实际上就是一个构造方法,那就是public FileInutStream(File file),原因看源码,如下

public FileInutStream(String name){

    this(name != null?new File(name) :null);

}

  public FileInutStream(File file){

    this(file);

}

方法描述:

   public int read() :从输入流中读取单个字节数据,并且返回它的integer,这个值在0-255之间,如果等于-1,则表示读完

     public int read(byte[] b,int byteOffset,int byteCount): 每次从这个流中读取byteCount(b.length)个字节到b中,从第byteOffset个开始,读到b字节数组中

    public  void close():关闭这个流并且释放这个流中的所有资源

  

使用示例:

FileInputStream in = new FileInputStream("d:/a.txt");   //创建a.txt文件的输入流对象

int len = 0;

  byte[] buf = new byte[1024];  //创建一个大小为1024的字节数组作为容器buf

//采用一个while循环,

  while( len = in.read(buf) != -1){//如果没有读完,则将该输入流的数据持续读进buf字节数组

    String str = new String(buf,0,len);  //将字节流转化为字符流

    System.out.println(str);

  }

//读取单个字节数据,则返回该字节数据

public int read() throws IOException {
byte[] b = new byte[1];
return (read(b, 0, 1) != -1) ? b[0] & 0xff : -1;
}