文件字符流
字符流的两个抽象父类:字符输出流:Writer 和字符输入流:Reader
OutputStreamWriter 类的成员方法
public void write(int c):写一个字符
public void write(char[] cbuf):写一个字符数组
public void write(char[] cbuf,int off,int len):写一个字符数组的一部分
public void write(String str):写一个字符串
public void write(String str,int off,int len):写一个字符串的一部分
flush():刷新缓冲区
close():关闭流对象
BufferedReader/BufferedWriter,字符缓存流(处理流),与BufferedInputStream/BufferedOutputStream类似,增加了缓存机制,大大提高了读写文本文件的效率。
BufferedReader/BufferedWriter也可以对FileReader/FileWriter进行装饰,然后继续使用read()方法。
public static void main(String[] args) throws IOException {
File f1=new File("d:/a.txt");
BufferedReader br=new BufferedReader(new FileReader(f1));
//可以按行去读取
String line= br.readLine();//一直读取,直到读取到了换行符为止
System.out.println(line);
String line1= br.readLine();
System.out.println(line1);
//读取到最后一行在读取获取的是null
String line2= br.readLine();
System.out.println(line2);
}
输入流:Reader
public class ReaderTest {
public static void main(String[] args) throws IOException {
File f1=new File("d:/a.txt");
// Reader r=new FileReader(f1);
BufferedReader inp=new BufferedReader(new FileReader(f1));
// int n= inp.read();//所有的中文字符按照一个字符处理,每次读取一个字符,把该字符转换成对应的编码值
// System.out.println((char)n);
// int n1= inp.read();
// System.out.println((char)n1);
// //使用缓冲区读取多个字符
char[] c=new char[10];
int n = inp.read(c);//次最多读取buffer数组长个字符,把读取到的字符存入buffer数组中,返回的是实际读取到的字符数system.out.println(n);
System.out.println(n);
System.out.println(Arrays.toString(c));
char[] c1=new char[10];
int n1=inp.read(c1);
System.out.println(n1);
System.out.println(Arrays.toString(c1));
}
}
输出流:Writer
public static void main(String[] args) throws IOException {
File f2=new File("D:/b.txt");
if(!f2.exists()){
f2.createNewFile();
}
//定义一个字符输出流,向f2文件写入内容
Writer out=new FileWriter(f2,true);
out.write(97);
out.write((int)'中');
char[] c={'河','南','南','阳'};
out.write(c);
out.write("奥里给");
out.write("abcdef",0,3);
out.flush();//字符输出流有缓冲区的概念 需要刷新缓冲区才更新硬盘
out.close();
}