Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properly reading files with FileReader and BufferedReader in Java

I am trying to learn how to use read files using FileReader in Java however I get persistent errors. I am using Eclipse and I get a red error indicating that The constructor FileReader(File) is undefined and The constructor BufferedReader(FileReader) is undefined; however, I do not know where this error is originating from because I am using the right libraries and statements.

I get the following error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    The constructor FileReader(File) is undefined
    The constructor BufferedReader(FileReader) is undefined
    at FileReader.main(FileReader.java:17)

My code is below:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;


public class FileReader {

    public static void main(String[] args) {

        File file = new File("example.txt");

        BufferedReader br = null;

        try {
            FileReader fr = new FileReader(file);
            br = new BufferedReader(fr);

            String line;

            while( (line = br.readLine()) != null ) {
                System.out.println(line);
            }

        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + file.toString());
        } catch (IOException e) {
            System.out.println("Unable to read file: " + file.toString());
        }
        finally {
            try {
                br.close();
            } catch (IOException e) {
                System.out.println("Unable to close file: " + file.toString());
            }
            catch(NullPointerException ex) {
            }
        }



    }

}

For extra context (Sorry about the size but I believe you can zoom in. You can see where to red errors are on the left of the line): enter image description here


1 Answers

The problem is that you named your own class FileReader, and it's conflicting with the java.io.FileReader you want to use. This is what the red line under the import is telling you: Importing won't work because you have a different class with the same name that's shadowing the import. Change the name of your class.

like image 158
chrylis -cautiouslyoptimistic- Avatar answered Oct 25 '25 16:10

chrylis -cautiouslyoptimistic-



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!