使用Java中的FileReader和BufferedReader正确读取文件

4
我试图学习如何在Java中使用FileReader读取文件,但是我一直遇到错误。我正在使用Eclipse,出现了红色的错误提示,显示"The constructor FileReader(File) is undefined"和"The constructor BufferedReader(FileReader) is undefined",但是我不知道这个错误来自哪里,因为我使用了正确的库和语句。
我得到了以下错误:
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)

以下是我的代码:

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) {
            }
        }



    }

}

为了更好的理解(抱歉图片有些大,但我相信您可以缩放。您可以在行左侧看到红色错误的位置):

enter image description here
2个回答

10
问题在于你给自己的类命名为FileReader,这与你想要使用的java.io.FileReader产生了冲突。这就是导入下面的红线提示你的原因: 导入不起作用,因为你有一个与导入重名的不同类覆盖了它。请更改你的类名称。

在处理文件读取操作时,FileReader不应该是类名。 - Manish

2

尝试以下操作:

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 {
            java.io.FileReader fr = new java.io.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) {
            }
        }



    }

}

实际上,你的类FileReader隐藏了java.io.FileReader。现在应该可以正常工作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接