首页 > 其他 > 详细

I/O输入流基础之FileInputStream

时间:2019-04-27 21:17:58      阅读:136      评论:0      收藏:0      [点我收藏+]

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;
}

 

  

  

I/O输入流基础之FileInputStream

原文:https://www.cnblogs.com/toBlog/p/10780352.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!