基础知识
FileReader 和 FileWriter都是字符输入输出流,他们的父类为Reader类和Writer类。
代码块
import java.io.*;
import java.util.Scanner;
public class test {
public static void main(String[] args) throws IOException {
//创建文件
File file = new File("G:\\file.txt");
if(!file.exists()){
file.createNewFile();
System.out.println(file.getName()+"文件已创建!");
}
try{
FileWriter fw = new FileWriter(file);
FileReader fr = new FileReader(file);
Scanner in = new Scanner(System.in);
//从控制台输入数据
String s = new String();
while(true){
s = in.nextLine();
if(s.equals("")){
break;
}
fw.write(s);
fw.flush();
}
//写入文件
fw.write(s);
fw.flush();//刷新输出流将数据写入文件
//读取文件
char []byt = new char[2014];//设置字符数字作为缓冲区
int len = fr.read(byt);//fr.read(byt)返回byt的字符数
System.out.println(new String(byt,0,len));
//关闭流
fw.close();
fr.close();
}catch(Exception E){
}
}
}
运行结果