FileReader的简单使用
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Demo01 {
public static void main(String[] args) throws IOException {
FileReader fr=new FileReader("a.txt");
int len=0;
while ((len=fr.read())!=-1) {
System.out.println((char)len);
}
}
}
FileWriter的简单使用
package com.zifu;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Demo02 {
public static void main(String[] args)throws IOException {
FileWriter fw=new FileWriter("a.txt");
Scanner input=new Scanner(System.in);
System.out.println("请输入内容:");
while (true) {
String content=input.nextLine();
fw.write(content);
fw.write("\r\n");
if(content.equals("quit")) {
break;
}
}
fw.close();
}
}
案例:字符流的拷贝
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Demo03 {
public static void main(String[] args)throws IOException{
test2();
}
public static void test1() throws FileNotFoundException, IOException {
FileReader fr=new FileReader("a.txt");
FileWriter fw=new FileWriter("b.txt");
int c=0;
while ((c=fr.read())!=-1) {
fw.write(c);
}
fw.close();
fr.close();
}
public static void test2() throws FileNotFoundException, IOException {
FileReader fr=new FileReader("a.txt");
FileWriter fw=new FileWriter("b.txt");
char[] buf=new char[8*1024];
int len=0;
while ((len=fr.read(buf))!=-1) {
fw.write(buf);
}
fw.close();
fr.close();
}
}