Skip to content

BufferedWriter&BufferedReader

不重新实例化相关reader writer

Java
File file = new File("D:\\test.txt");
if(!file.exists()){
    file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("第一行");
bufferedWriter.newLine();
bufferedWriter.flush();
System.out.println(bufferedReader.readLine());
file.delete();
file.createNewFile();
bufferedWriter.write("删除重建file后尝试写入");
bufferedWriter.newLine();
bufferedWriter.flush();
System.out.println(bufferedReader.readLine());

控制台输出

Java
第一行
删除重建file后尝试写入

test.txt文件内容

Java
第一行
删除重建file后尝试写入

重新实例化相关reader writer

Java
File file = new File("D:\\test.txt");
if(!file.exists()){
    file.createNewFile();
}
FileWriter fileWriter = new FileWriter(file);
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("第一行");
bufferedWriter.newLine();
bufferedWriter.flush();
System.out.println(bufferedReader.readLine());
file.delete();
file.createNewFile();
/* 差异代码 start */
fileWriter = new FileWriter(file);
fileReader = new FileReader(file);
bufferedReader = new BufferedReader(fileReader);
bufferedWriter = new BufferedWriter(fileWriter);
/* 差异代码 end */
bufferedWriter.write("删除重建file后,重新实例化相关reader writer 尝试写入");
bufferedWriter.newLine();
bufferedWriter.flush();
System.out.println(bufferedReader.readLine());

控制台输出

Java
第一行
删除重建file后,重新实例化相关reader writer 尝试写入

test.txt文件内容

Java
删除重建file后,重新实例化相关reader writer 尝试写入