简体   繁体   中英

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. If I change System.out.println with Writer, it will not be null. why?

You are overwriting the same file when you do 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. When the writer is initialized, the file is in use so you can't read it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM