IO流详解

打印 上一主题 下一主题

主题 884|帖子 884|积分 2652

一、IO流概述

1.原理

![](https://img2022.cnblogs.com/blog/2901531/202206/2901531-20220621172751004-1385246087.png)2.流的分类



3.流的体系,蓝底框为重点掌握的


二、IO流操作

1.节点流-字符流

(1).FileReader读入数据的基本操作

点击查看代码
  1. package com.Tang.io;
  2. import org.junit.Test;
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.io.FileReader;
  6. import java.io.IOException;
  7. public class IOTest {
  8.     @Test
  9.     public void test() {
  10.         FileReader fr = null;
  11.         //为了保证流资源一定可以执行关闭操作,需要使用try-catch-finally
  12.         //读入的文件一定要存在,否则就会报FileNotFoundException。
  13.         try {
  14.             //将Hello工程下的hello.txt文件内容读入程序中,并输出到控制台
  15.             //1.实例化File类对象,指明要操作的文件
  16.             File file = new File("hello.txt");
  17.             //2.提供具体的流
  18.             fr = new FileReader(file);
  19.             //3.数据的读入
  20.             //read():返回读入的一个字符,如果达到文件末尾,返回-1;否则返回字符的Ascall值
  21.             int data = fr.read();
  22.             while(data != -1){
  23.                 System.out.print((char)data);//读取文件第一个字符
  24.                 data = fr.read();//读取文件下一个字符
  25.             }
  26.         } catch (IOException e) {
  27.             e.printStackTrace();
  28.         } finally {
  29.             //4.流的关闭操作
  30.             try {
  31.                 if(fr != null)
  32.                     fr.close();
  33.             } catch (IOException e) {
  34.                 e.printStackTrace();
  35.             }
  36.         }
  37.     }
  38. }
复制代码
运行结果图

①.FileReader对read()操作升级:使用read的重载方法

代码中for循环处如果写为i < cubf.length会出现一下问题![](https://img2022.cnblogs.com/blog/2901531/202206/2901531-20220622150055674-2067087883.png)点击查看代码[code]//对read()操作升级:使用read的重载方法    @Test    public void test1(){        FileReader fr = null;        try {            //1.File类的实例化            File file = new File("hello.txt");            //2.FileReader流的实例化            fr = new FileReader(file);            //3.读入的操作            //read(char[] cbuf):返回每次读入cbuf数组中的字符的个数,当读到文件末尾时返回-1            char[] cbuf = new char[5];//相当于一个容量池,每次能从文件能读出的最大字符数            int len;            while((len = fr.read(cbuf) )!= -1){                //方式一:                //错误写法//                for (int i = 0; i

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

盛世宏图

金牌会员
这个人很懒什么都没写!
快速回复 返回顶部 返回列表