字符流
1.字节流读取中文的问题
1.注意:
字节流是万能流,更侧重于文件复制,但是尽量不要边读边看
2.原因:
UTF-8:一个汉字占3个字节
GBK:一个中文占2个字节
如果按照字节读取,每次读取的字节没有构成一个汉字的字节数,就直接输出,汉字是显示不了的
3.解决:
将文本文档中的内容,按照字符去操作
话说回来:
1.按照字符去操作编码也要一致,如果不一致,照样会乱码
2.按照字节流去操作即使编码一致,边读边看,也有可能乱码
2.FileReader的介绍以及使用
字符流专门操作文本文档的,但是复制操作不要用字符流,要用字节流
1.概述:字符输入流 -> Reader -> 是一个抽象类
子类:FileReader
2.作用:将文本文档中的内容读取到内存中来
3.构造:
FileReader(File file)
FileReader(String path)
4.方法:
int read() -> 一次读取一个字符,返回的是读取字符对应的int值
int read(char[] cbuf) -> 一次读取一个字符数组,返回的是读取个数
int read(char[] cbuf, int off, int len) -> 一次读取一个字符数组一部分,返回的是读取个数
cbuf:读取的数组
off:从数组的哪个索引开始读
len:读多少个
void close() -> 关闭资源
private static void method01() throws IOException {
FileReader fr = new FileReader("module21\\1.txt");
int len;
while((len = fr.read())!=-1){
System.out.println((char) len);
}
fr.close();
}
private static void method02()throws Exception {
FileReader fr = new FileReader("module21\\1.txt");
char[] chars = new char[2];
int len;
while((len = fr.read(chars))!=-1){
System.out.println(new String(chars,0,len));
}
fr.close();
}
3.FileWriter的介绍以及使用
1.概述:字符输出流 -> Writer -> 抽象类
子类:FileWriter
2.作用:将数据写到文件中
3.构造:
FileWriter(File file)
FileWriter(String fileName)
FileWriter(String fileName, boolean append) -> 追加,续写
4.方法:
void write(int c) -> 一次写一个字符
void write(char[] cbuf) 一次写一个字符数组
void write(char[] cbuf, int off, int len) 一次写一个字符数组一部分
void write(String str) 直接写一个字符串
void flush() :将缓冲区中的数据刷到文件中
void close() 关流
5.注意:FileWriterr底层自带一个缓冲区,我们写的数据会先保存到缓冲区中,所以我们需要将缓冲区中的数据刷到文件中
public class Demo01FileWriter {
public static void main(String[] args)throws Exception {
FileWriter fw = new FileWriter("module21\\2.txt");
fw.write("千山鸟飞绝\r\n");
fw.write("万径人踪灭\r\n");
fw.write("孤舟蓑笠翁\r\n");
fw.write("独钓寒江雪\r\n");
//fw.flush();
fw.close();
}
}
4.FileWriter的刷新功能和关闭功能
flush():将缓冲区中的数据刷到文件中,后续流对象还能继续使用
close():先刷新后关闭,后续流对象不能使用了
5.IO异常处理的方式
public class Demo01Exception {
public static void main(String[] args) {
FileWriter fw = null;
try{
fw = new FileWriter("module21\\3.txt");
fw.write("你好");
}catch (Exception e){
e.printStackTrace();
}finally {
//如果fw不为null,证明new出来了所以需要close;相反不需要close
if (fw!=null){
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
6.JDK7之后io异常处理方式
1.格式:
try(IO对象){
可能出现异常的代码
}catch(异常类型 对象名){
处理异常
}
2.注意:
以上格式处理IO异常,会自动关流
public class Demo02Exception {
public static void main(String[] args) {
try(FileWriter fw = new FileWriter("module21\\4.txt");){
fw.write("你好");
}catch (Exception e){
e.printStackTrace();
}
}
}