Java-IO之流的分类

126 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第15天,点击查看活动详情

InputStream & Reader

  • InputStream 和 Reader 是所有输入流的基类。
  • InputStream(典型实现:FileInputStream)
  • int read()
  • int read(byte[] b)
  • int read(byte[] b, int off, int len)
  • Reader(典型实现:FileReader)
  • int read()
  • int read(char [] c)
  • int read(char [] c, int off, int len)
  • 程序中打开的文件 IO 资源不属于内存里的资源,垃圾回收机制无法回收该资源,所以应该显式关闭文件 IO 资源。
  • FileInputStream 从文件系统中的某个文件中获得输入字节。FileInputStream 用于读取非文本数据之类的原始字节流。要读取字符流,需要使用 FileReader

InputStream

- nt read()

  • 从输入流中读取数据的下一个字节。返回 0 到 255 范围内的 int 字节值。如果因为已经到达流末尾而没有可用的字节,则返回值 -1。
  • int read(byte[] b)
  • 从此输入流中将最多 b.length 个字节的数据读入一个 byte 数组中。如果因为已经到达流末尾而没有可用的字节,则返回值 -1。否则以整数形式返回实际读取的字节数。
  • int read(byte[] b, int off,int len)
  • 将输入流中最多 len 个数据字节读入 byte 数组。尝试读取 len 个字节,但读取的字节也可能小于该值。以整数形式返回实际读取的字节数。如果因为流位于文件末尾而没有可用的字节,则返回值 -1。
  • public void close() throws IOException关闭此输入流并释放与该流关联的所有系统资源。

read方法

  • 方式一
      //1File类的实例化
        File file=new File("hello.txt");
        //FileReader流的实例化
        FileReader fr =new FileReader(file);
        //读入的操作
        //read(char [] c):返回每次读入c数组中的字符的个数。如果达到文件的末尾,返回 -1
        char[]c=new char[5];
        int len;
        while ((len=fr.read(c))!=-1) {
            for (int i=0;i<len;i++){
                System.out.print(c[i]);
            }
        }
        //资源的关闭
        fr.close();

    }
}
  • 方式二
char[] c = new char[5];
int len;

while ((len = fr.read(c)) != -1) {
    String str = new String(c, 0, len);
    System.out.print(str);

}