Java之字符输入流Reader及代码精析

一:Reader类

  • Reader是所有字符输入流的超类。它提供了读取字符流的基本方法,如read(), read(char[] cbuf, int off, int len)等
  • 由于Reader是抽象类,通常使用它的子类如FileReader, BufferedReader, InputStreamReader等来创建字符输入流对象。

二:Reader常用方法

  • int read(): 读取单个字符。如果已到达流的末尾,则返回-1。
  • int read(char[] cbuf): 读取字符到指定的字符数组。返回读取的字符数,如果已到达流的末尾,则返回-1。
  • int read(char[] cbuf, int off, int len): 读取字符到指定字符数组。返回读取的字符数,如果已到达流的末尾返回-1。
  • void close(): 关闭流并释放与之相关联的系统资源。

三:常见子类

  • FileReader 用来读取字符文件的实现类
public FileReader(String fileName) throws FileNotFoundException {
    super(new FileInputStream(fileName));
}

public FileReader(File file) throws FileNotFoundException {
    super(new FileInputStream(file));
}

四:代码精析

package chapter12;

import java.io.File;
import java.io.FileReader;
import java.io.Reader;

public class ReaderDemo {
    public static void main(String[] args) {
        String dir = "/Users/mz/IdeaProjects/xdclass-count/src/chapter12";
        String name = "abc.txt";

        File file = new File(dir, name);
        try (Reader reader = new FileReader(file)) {

            char[] buf = new char[1024];
            int numCharsRead;

            while((numCharsRead = reader.read(buf))!= -1){
                String str = new String(buf,0,numCharsRead);
                System.out.println(str);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

/**
运行结果:
中新网8月27日电 据中央气象台官方微博消息,
今年第10号台风“珊珊”8月27日17时由强台风级加强为超强台风级,
其中心位于日本九州岛偏南方大约495公里的西北太平洋洋面上,
中心附近最大风力16级(52米/秒) 。
预计,台风“珊珊”将以每小时5~10公里的速度向偏北方向移动,
逐渐向日本九州岛沿海靠近,并将于29日白天在日本九州岛一带沿海登陆(台风级或强台风级,13~14级,40~45米/秒),
之后转向东北方向移动,穿过日本四国岛和本州岛,强度逐渐减弱。
*/
  • 5
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

竹意雅韵(马)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值