介绍
字符流操作单位是一个字符(不是一个字节),读写文本文件很方便
使用字节流来操作中文的时候非常不方便,容易产生乱码
字符流——文件输入流(FileReader)
构造方法:
public FileReader(String fileName)throws FileNotFoundException
public FileReader(File file)throws FileNotFoundException
Code:
注意:尝试使用不存在的抽象路径 FileNotFoundException 报错
读取单个字符
Reader reader = new FileReader("C:/test.txt");
int read = reader.read();
System.out.println((char)read);
循环读取
int i ;
while ((i=reader.read()) != -1) {
System.out.println((char)i);
}
读取到数组里
char[] c = new char[1024];
int n;
while ((n =reader.read(c)) != -1) {
System.out.println(new String(c,0,n));
}
字符流——文件输出流(FileWriter)
构造方法:
public FileWriter(File file)throws IOException 会覆盖
public FileWriter(File file,boolean append)throws IOException append为true时会追加内容而不是覆盖
读取单个和循环读取跟FileOutputStream差不多
Writer fw = new FileWriter("C:\\Users\\maple\\Desktop\\itsourcejava\\2018-12-18-IO-DAY23\\xx\\e.txt");
fw.write("this is a test!");
//FileWriter 需要调用flush刷新才会有内容 close方法不但会关闭流也会刷新缓存
//fw.flush();
fw.close();
字符流和字节流的区别
- 操作的单位不一样,一个是字节,一个是字符
- 操作中文的时候使用字符流更方便, 字节流更广泛:文本,视频,音频,图片…
- 字符流中有可以直接写字符串的方法
- 字节输出流 : 程序 —> 磁盘文件 如果不关闭流也会写入
- 字符输出流 :程序 —> 缓冲 —> 磁盘文件 如果不关闭流或者刷新缓冲区,不会写入文件
- 字符输出流,关闭的时候会先刷新,关闭之后不能够在操作,刷新之后可以继续操作
什么时候会用到刷新 : 写入的数据,比较多,可以在中途手动调用刷新的方法提交数据