InoutStream和outPutStream在读取文件的时候操作的都是字节,同字节流一样字符流也有两个抽象的顶级父类。Reader和Writer。其中主要有FileReader/Writer和BufferderReader/Writer常用子类
一、Reader:字符输入流FileReader
package com.package18;
import java.io.FileReader;
import java.io.IOException;
public class ReaderDemo {
public static void main(String[] args)throws IOException {
FileReader reader= new FileReader("./out.txt");
int le=0;
while ((le=reader.read())!=-1){
System.out.print((char) le);
}
}
}
二、Writer:字符输出流FileWriter
package com.package18;
import java.io.FileWriter;
import java.io.IOException;
public class WriterDemo {
public static void main(String[] args) throws IOException {
FileWriter fileWriter = new FileWriter("./text/writer.text");
String str="轻轻的我走了,正如我轻轻的来;\n" +
"我轻轻的招手,作别西天的云彩。\n" +
"那河畔的金柳,是夕阳中的新娘;\n" +
"波光里的艳影,在我的心头荡漾。\n" +
"软泥上的青荇,油油的在水底招摇;\n" +
"在康河的柔波里,我甘心做一条水草!\n" +
"那榆荫下的一潭,不是清泉,是天上虹;\n" +
"揉碎在浮藻间,沉淀着彩虹似的梦。\n" +
"寻梦?\n" +
"撑一支长篙,向青草更青处漫溯;\n" +
"满载一船星辉,在星辉斑斓里放歌。\n" +
"但我不能放歌,悄悄是别离的笙箫;\n" +
"夏虫也为我沉默,沉默是今晚的康桥!\n" +
"悄悄的我走了,正如我悄悄的来;\n" +
"我挥一挥衣袖,不带走一片云彩。";
fileWriter.write(str);
fileWriter.close();
}
}
三、字符缓冲流:
①:使用字符缓冲区来复制文件:
public class CopyDemo2 {
public static void main(String[] args)throws IOException {
FileReader reader = new FileReader("./text/writer.text");
FileWriter fileWriter = new FileWriter("./text/writer2.text");
int temp=0;
char []buff=new char[1024];
while ((temp=reader.read(buff))!=-1){
fileWriter.write(buff,0,temp);
}
reader.close();
fileWriter.close();
}
}
<br />②:BufferdReader和BufferdWiter两个类也同样在其内部定义了8192大小的字节数组。
public class CopyDemo3 {
public static void main(String[] args)throws IOException {
BufferedReader bufferedReader = new BufferedReader(new FileReader("./text/writer.text"));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("./text/writer3.text"));
String str=null;
while ((str=bufferedReader.readLine())!=null){
bufferedWriter.write(str);
bufferedWriter.newLine();//换行符,根据不同的操作系统生成不同的换行符
}
bufferedReader.close();
bufferedWriter.close();
}
}