IO流部分记忆体系整理
这篇记录的是InputStreamReader、FileReader、BufferedReader
1.InputStreamReader【处理字符流。方向:文件向内存】
父类Reader
InputStreamReader类对象下面简写为in
(1)用指定输入流in,接收读取到的文件内容
(2)最后通过close()方法结束读取
(3)字符数组长度问题:
读取到的内容用字符数组chars接收,chars不够长的情况这里没写
代码例子:
package com.cskaoyan.bytestream.transf;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @description: 转换流读取数据
* @author: 景天老师
**/
public class Demo2 {
public static void main(String[] args) throws IOException {
// 创建转换输入流
InputStreamReader in = new InputStreamReader(new FileInputStream("a.txt"));
// 读取数据
readSingle(in);
// 读取多个字符 读取的字符数,如果已到达流的末尾,则返回 -1
//readMuti(in);
in.close();
}
private static void readMuti(InputStreamReader in) throws IOException {
char[] chars = new char[1024];//读取输入流in内容到chars字符数组
int readCount;
while ((readCount = in.read(chars)) != -1) {
System.out.println(new String(chars,0,readCount));
}
}
private static void readSingle(InputStreamReader in) throws IOException {
int readData = in.read();
System.out.println(((char) readData));
int readData2 = in.read();
System.out.println(((char) readData2));
int readData3 = in.read();
System.out.println(((char) readData3));
int readData4 = in.read();
//System.out.println(((char) readData4));//换行
System.out.println(readData4);
//System.out.println((char)13);
}
}
2.FileReader【处理字符流。方向:文件向内存】
父类Reader
FileReader类对象下面简写为fr
(1)用指定输入流fr,接收读取到的文件内容
(2)最后通过close()方法结束读取
(3)字符数组长度问题:同上这里没写
代码例子:
package com.cskaoyan.bytestream.simple;
import java.io.FileReader;
import java.io.IOException;
/**
* @description:
* @author: 景天老师
**/
public class Demo2 {
public static void main(String[] args) throws IOException {
//public FileReader(String fileName)
//public FileReader(File file)
FileReader fr = new FileReader("a.txt");
char[] chars = new char[1024];
//这里没有试过chars长度不够的情况:
//比如:a.txt里面有4个字母,chars只有2个位置
//想想老师上课那个abcd -> efcd的例子
//但是,那个例子好像是输出流,这里讨论的是FileReader,是输入流
int readCount = fr.read(chars);
System.out.println(new String(chars,0,readCount));
fr.close();
}
}
3.BufferedReader【处理字符流。方向:文件向内存】
父类Reader
BufferedReader类对象下面简写为br
(1)用指定输入流br,接收读取到的文件内容
(2)最后通过close()方法结束读取
(3)用String类接收1行:br对象调用readLine()方法,括号内没有参数,得到文件中1行内容
读取到的内容用String类型变量line接收
package com.cskaoyan.buffer;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Demo2 {
public static void main(String[] args) throws IOException {
//创建缓冲输入流对象
BufferedReader br = new BufferedReader(
new FileReader("a.txt"));
//读取一个文本行readLine方法
//read1(br);//这里包装了一个read1()方法,里面还是readLine()方法
String line;
while ((line = br.readLine()) != null) {
//如果文件有很多行:
//第一次调用完readLine()方法会继续判断line的值
//但是line又会指向一个新字符串,是br调用readLine()读取的新一行
System.out.println(line);
}
br.close();
}
private static void read1(BufferedReader br) throws IOException {
String s = br.readLine();//传入br对象,调用它的readLine()方法
System.out.println(s);
String s2 = br.readLine();
System.out.println(s2);
}
}