字节流的缺点
- 基本上任何文件都能处理,但是对于纯文本的文件处理会出问题
- 在读文件的时候采用byte数组类型的参数的时候,有可能正好截取到了中文分割,这时候再写入就会造成写入的文件根读的文件不一致
字符流,用来处理纯文本的比较好,什么是纯文本?右键用记事本打开不会乱码即纯文本;
FileReader
public static void main(String[] args) throws IOException{
FileReader fileReader = new FileReader('读取的文件');
int code = fileReader.read();
while(code != -1){
System.out.println((char)code);
code = fileReader.read();
}
}
public static void main(String[] args) throws IOException{
FileReader fileReader = new FileReader('读取的文件');
char[] chars = new char[5];
int count = fileReader.read(chars);
while(count != -1){
String string = new String(chars,0,count);
System.out.print(string);
count = fileReader.read(chars);
}
}
复制代码
字符流的写操作
public static void main(String[] args) throws IOException{
FileReader fr = new FileReader("src/a.html");
FileWriter fw = new FileWriter("src/d.txt",true);
char[] chars = new char[5];
int count = fr.read(chars);
while (count != -1){
fw.write(chars,0,count);
fw.flush();
count = fr.read(chars);
}
fr.close();
fw.close();
}
复制代码
………………………………