[英]Why this pojo program “readline” always return null?
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());
}
The day.txt I have wrote some words before execute. 在执行之前,day.txt我已经写了一些字。 If I change System.out.println with Writer, it will not be null.
如果我用Writer更改System.out.println,它将不会为null。 why?
为什么?
You are overwriting the same file when you do new FileWriter("day.txt");
当您执行
new FileWriter("day.txt");
时,您将覆盖同一文件new FileWriter("day.txt");
change your code to 将您的代码更改为
BufferedReader reader = new BufferedReader(new FileReader("day.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("day-new.txt"));
System.out.println(reader.readLine());
Create the writer instance after printing out to console. 打印到控制台后,创建writer实例。 When the writer is initialized, the file is in use so you can't read it.
初始化编写器后,该文件正在使用中,因此您无法读取它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.