Search code examples
javafilereaderfilewriter

Java: FileReader and FileWriter not working together


So, I'm trying to make a program that can write and then read the exact same text file using only FileWriter and FileReader, but for some reason, when I put both of these classes at the same code, FileWriter works properly, but FileReader does not, and I get an empty output.

import java.io.*;
import java.util.Scanner;
public class ex2 {
    public static void main(String[] args) {
        File file = new File("C:\\a.txt");
        Scanner scanner = new Scanner(System.in);
        try {
            FileReader reader = new FileReader(file);
            FileWriter writer = new FileWriter(file);
            writer.write(scanner.nextLine());
            int ch;
            while ((ch = reader.read()) != -1) {
                System.out.println((char)ch);
            }
            scanner.close();
            reader.close();
            writer.close();
        } catch (Exception e) {

        }

    }
}

That's the code I'm talking about. I can write anything to a.txt, but reader does not seem to be able to read a thing. The weird part is, if I use the exact same code but without the file writing parts, FileReader works normally as it should. What am I doing wrong? Thanks in advance!


Solution

  • FileWriter objects are buffered. That means they won't write everything you give them as soon as you call write. They'll wait until they have a certain amount to write and then write it all at once. Just add this line:

    writer.flush();
    

    between your writing and your reading.