为什么这个pojo程序“ readline”总是返回null?

时间:2019-01-30 07:57:31

标签: java

public static void main(String[] args) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader("day.txt"));
    BufferedWriter writer = new BufferedWriter(new FileWriter("day.txt"));
    System.out.println(reader.readLine());
}

day.txt我在执行之前已经写了一些字。如果我用Writer更改System.out.println,它将不会为null。为什么?

2 个答案:

答案 0 :(得分:4)

执行new FileWriter("day.txt");

时,您正在覆盖同一文件

将代码更改为

BufferedReader reader = new BufferedReader(new FileReader("day.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("day-new.txt"));
System.out.println(reader.readLine());

答案 1 :(得分:0)

打印到控制台后,创建writer实例。编写器初始化后,该文件正在使用中,因此您无法读取它。