Search code examples
javafilereaderfile-read

Filereader.read() method not working


I have written the following code that creates a file, adds text to it and then reads the file. My problem is that on execution, the contents of the file are not displayed on the screen, though the contents are added in the text file.

Following is my code

import java.io.*;
class prc4{
public static void main(String args[]){
try{
    File f = new File("C:\\Program Files\\Java\\jdk1.8.0_25\\bin\\file1.txt");
    if (f.createNewFile()){
        System.out.println("File is created!");
        }else{
        System.out.println("File already exists.");
        }
    FileWriter f1 = new FileWriter("file1.txt");
    f1.write("Hello World. This is a sample text file!");
    FileReader f2 = new FileReader("file1.txt");
    int x = f2.read();
    while(x != -1){
        System.out.println((char)x);
        x = f2.read();
    }
    f1.close();
    f2.close();
}catch(Exception e){    }
}
}

Output: enter image description here

enter image description here

In the text file:

enter image description here


Solution

  • You need to close, or at least flush, the writer before you read from the file. Writing to files is buffered, and so the contents are not actually in the file yet when you are reading from it. I recommend closing the writer using a try-with-resources construct:

    try (FileWriter f1 = new FileWriter("file1.txt"))
        {
        f1.write("Hello World. This is a sample text file!");
        }
    
    try (FileReader f2 = new FileReader("file1.txt");)
        {
        int x = f2.read();
        while(x != -1){
            System.out.println((char)x);
            x = f2.read();
        }
        }
    

    Note, too, that you are calling println() for each character, which means that each character will be printed on a separate line. This may be what you want, or you may want to call print() instead.