廖雪峰Java6 IO编程-3Reader和Writer-1Reader
1.java.io.Reader和java.io.InputStream的区别
InputStream | Reader |
---|---|
字节流,以byte为单位 | 字符流,以char为单位 |
读取字节(-1,0-255):int read() | 读取字符,(-1,0-65535):int read() |
读到字节数组:int read(byte[] b) | 读到字符数组:int read(char[] c) |
int read(byte[] b, int off, int len) | int read(char[] c, int off, int len) |
2.Reader
java.io.Reader是所有字符输入流的超类:
- int read():
* 读取下一个字节,并返回字符的int值 (0-65535)
* 如果已读取到末尾,返回-1
* read()方法是阻塞(blocking)的,必须等待read()方法返回才能执行下一行代码 - int read(char[] c):读取若干字符并填充到char[]数组,返回读取的字符数
- int read(char[] c, int off, int len):指定char[]数组的偏移量和最大填充数
- void close():关闭Reader
2.1完整的读取一个Reader的所有字符:
方法1:手动关闭
方法2:使用try...finally
方法3:使用try(resource)自动关闭
public class Main {
public static void main(String[] args) throws IOException,ClassNotFoundException {
String file = "./src/main/java/com/testList/Person.txt";
readFile1(file);
System.out.println();
readFile2(file);
System.out.println();
readFile3(file);
}
static void readFile1(String file) throws IOException{
//手动关闭
Reader reader = new FileReader(file);
int n;
while((n=reader.read())!=-1){
System.out.print((char)n);
}
reader.close();
}
static void readFile2(String file) throws IOException{
//使用finally关闭
Reader reader = null;
try{
reader = new FileReader(file);
int n;
while((n=reader.read())!=-1){
System.out.print((char)n);
}
}finally {
if (reader!=null){
reader.close();
}
}
}
static void readFile3(String file) throws IOException{
//自动关闭
try(Reader reader = new FileReader(file)){
int n;
while((n=reader.read())!=-1){
System.out.print((char)n);
}
}
}
}



4.总结:
- Reader定义了所有字符输入流的超类
- FileReader实现了文件字符流输入
- CharArrayReader在内容中模拟一个字符流输入
- Reader是基于InputStream构造的:
* FileReader使用系统默认编码,无法指定编码
* 可以通过InputStreamReader指定编码 - 使用try(resource)保证Reader正确关闭
分类:
java纯小白,绕行
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!