|NO.Z.00077|——————————|BigDataEnd|——|Java&IO流.V04|——|Java.v04|IO流.v04|filereader类|概念使用|
一、FileReader的概念和基本使用
### --- 基本概念
——> java.io.FileReader类主要用于从文本文件读取文本数据内容。
二、常用的方法
方法声明 | 功能介绍 |
FileReader(StringfileName) | 根据参数指定的文件名构造对象 |
int read() | 读取单个字符的数据并返回,返回-1表示读取到末尾 |
int read(char[] cbuf, intoffset, int length) | 从输入流中将最多len个字符的数据读入一个字符数组中, 返回读取到的字符个数,返回-1表示读取到末尾 |
int read(char[] cbuf) | 从此输入流中将最多 cbuf.length 个字符的数据读入字符数组中, 返回读取到的字符个数,返回-1表示读取到末尾 |
void close() | 关闭流对象并释放有关的资源 |
三、编程使用
package com.yanqi.task17;
import java.io.FileReader;
import java.io.IOException;
public class FileReaderTest {
public static void main(String[] args) {
FileReader fr = null;
try {
// 1.构造FileReader类型的对象与d:/a.txt文件关联
//fr = new FileReader("d:/a.txt");
fr = new FileReader("d:/b.txt");
// 2.读取数据内容并打印
/*
int res = fr.read();
System.out.println("读取到的单个字符是:" + (char)res); // 'a'
*/
int res = 0;
while ((res = fr.read()) != -1) {
System.out.println("读取到的单个字符是:" + (char)res + ",对应的编号是:" + res);
}
// 准备一个字符数组来保存读取到的数据内容
// char[] cArr = new char[5];
// 期望读满字符数组中的一部分空间,也就是读取3个字符放入数组cArr中下标从1开始的位置上
/*int res = fr.read(cArr, 1, 3);
System.out.println("实际读取到的字符个数是:" + res); // 3
for (char cv : cArr) {
System.out.println("读取到的单个字符是:" + (char)cv); // 啥也没有 a e l 啥也没有
}*/
// 期望读满整个字符数组
/*int res = fr.read(cArr);
System.out.println("实际读取到的字符个数是:" + res); // 5
for (char cv : cArr) {
System.out.println("读取到的单个字符是:" + (char)cv); // a e l l h
}*/
} catch (IOException e) {
e.printStackTrace();
} finally {
// 3.关闭流对象并释放有关的资源
if (null != fr) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
四、编译打印
D:\JAVA\jdk-11.0.2\bin\java.exe "-javaagent:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\lib\idea_rt.jar=54744:D:\IntelliJIDEA\IntelliJ IDEA 2019.3.3\bin" -Dfile.encoding=UTF-8 -classpath E:\NO.Z.10000——javaproject\NO.H.00001.javase\javase\out\production\javase com.yanqi.task17.FileReaderTest
Process finished with exit code 0
Walter Savage Landor:strove with none,for none was worth my strife.Nature I loved and, next to Nature, Art:I warm'd both hands before the fire of life.It sinks, and I am ready to depart
——W.S.Landor
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通