2014-03-30 60 views
2

我想學習如何在Java中使用FileReader讀取文件,但是我得到持久性錯誤。我正在使用Eclipse,並且我得到一個紅色錯誤,指出構造函數FileReader(File)未定義爲 ,構造函數BufferedReader(FileReader)未定義;然而,我不知道這個錯誤來自哪裏,因爲我正在使用正確的庫和聲明。用Java中的FileReader和BufferedReader正確讀取文件

我收到以下錯誤:

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

回答

1

請嘗試以下操作

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。上面應該現在工作

6

問題是,你命名你自己的類FileReader,它與你想要使用的java.io.FileReader相沖突。這就是導入之下的紅線告訴你的:導入不起作用,因爲你有一個與導入相同的名稱不同的類。改變你班級的名字。

+0

當我們處理文件讀取操作時,FileReader不應該是類名。 – Manish

相關問題