字符流FileReader
public static void main(String[] args) throws IOException {
FileReader fr=new FileReader("xxx.txt");
int b;
while((b=fr.read())!=-1){
System.out.print((char)b); //因为是中文,所以要强制转换
}
fr.close();
}
FileWriter
public static void main(String[] args) throws IOException {
FileWriter fw=new FileWriter("yyy.txt");
fw.write("大家好,hahaha");
fw.write(97); //会写一个 a 在文件yyy.txt中
fw.close();
}
字符流的拷贝
public static void main(String[] args) throws IOException {
FileReader fr=new FileReader("xxx.txt");
FileWriter fw=new FileWriter("yyy.txt");
int c;
while((c=fr.read())!=-1){
fw.write(c);
}
fr.close();
fw.close();
//writer类中有一个2K的缓冲区,如果不关流,就会将内容写到缓冲区里
}
带有数组的拷贝
public static void main(String[] args) throws IOException {
FileReader fr=new FileReader("xxx.txt");
FileWriter fw=new FileWriter("yyy.txt");
char[] arr=new char[1024];
int len;
while((len=fr.read(arr))!=-1){ //将文件上的数据读取到字符数组中
fw.write(len); //将字符数组中的数据写到文件上
}
fr.close();
fw.close();
}
带有缓冲区的字符流拷贝
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new FileReader("xxx.txt"));
BufferedWriter bw=new BufferedWriter(new FileWriter("zzz.txt"));
int b;
while((b=br.read())!=-1){
bw.write(b);
}
br.close();
bw.close();
}