@TOC
以字符为单位读写。
字符流只能用于 文本文件。(jpg等不能用)
文件流
节点流:
提供基本的文件读写。
FileReader:
FileWriter:
读:
public static void main(String[] args) throws IOException {
// 读
// 1.
FileReader fr = new FileReader("f:/data/a.txt");
// 2. 读 读到文件尾 返回 -1
System.out.println(fr.read());//每次读一字符,返回int值
System.out.println((char)fr.read());
System.out.println(fr.read());// 文件尾 返回-1
// 循环
int temp;
while((temp = fr.read()) != -1){
System.out.print((char)temp);
}
// 3.
fr.close();
}
写:
public static void main(String[] args) throws IOException {
// String s = "hello你好啊"; b.txt
// 1. true - 追加 false - 覆盖 (默认)
FileWriter fw = new FileWriter("f:/data/b.txt",true);
// 2. 写
String str = "hello你好啊";
fw.write(str);
// 3.
fw.close();
}
练习:
读取一个文件,逆序写入另一个文件中
package day0321;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TestFileReaderExam {
public static void main(String[] args) throws IOException {
// 读
// 1.
FileReader fr = new FileReader("f:/data/a.txt");
// 2.
StringBuilder sr = new StringBuilder();
int temp;
while((temp = fr.read()) != -1){
sr.append((char)temp);
}
// System.out.println(sr);
// 3
fr.close();
// 反转 写
// 1.
FileWriter fw = new FileWriter("f:/data/b.txt");
// 2.
String str = sr.reverse().toString();
fw.write(str);// String
// 3.
fw.close();
}
}
缓冲流
处理流。
提供缓冲区。
BufferedReader
BufferedWriter
public static void main(String[] args) throws IOException {
// 读
// 1
FileReader fr = new FileReader("f:/data/a.txt");
BufferedReader bfr = new BufferedReader(fr);
// 2. 一次读一行
System.out.println(bfr.readLine());
// System.out.println(bfr.readLine());// null
String temp;
while((temp = bfr.readLine()) != null){
System.out.println(temp);
}
// 3.
bfr.close();
}
Q.E.D.