2014-10-26 102 views
-1

我有這個讀取.txt文件並將它們存儲到String ArrayList中的FileIO類。但是,當我試圖打印出我的arrayList的內容,它似乎是空的。我在哪裏犯了一個錯誤?讀取文件並存儲到ArrayList中

public class FileIO 
{ 
    public ArrayList<String> readFile() throws IOException 
    { 
     ArrayList<String> al = new ArrayList<String>(); 
     try 
     { 
      File file = new File("example.txt"); 
      FileReader fileReader = new FileReader(file); 
      BufferedReader bufferedReader = new BufferedReader(fileReader); 

      String line; 
      while ((line = bufferedReader.readLine()) != null) 
      { 
       al.add(line); 
      } 
      fileReader.close(); 
     } 
     catch (IOException e) 
     { 
      e.printStackTrace(); 
     } 
     System.out.println(); 

     for (int i = 0; i < al.size(); i++) 
     { 
      System.out.println(al.get(i)); 
     } 

     return al; 
    } 
} 

public class Main 
{ 
    public static void main(String[] args) 
    { 
     FileIO fileIO = new FileIO(); 
     ArrayList<String> temp = fileIO.readFile();  
    } 
} 

我的txt文件的內容就是:

this is text1 
this is text2 
this is text3 
+0

你看到控制檯上的任何錯誤或異常我沒有看到上面代碼中的任何問題,除非你有空文件或文件不在類路徑或文件 – SMA 2014-10-26 16:02:55

+0

我試着「教一個人去釣魚」,而不是嘗試一個答案,我建議你閱讀Eric Lipper的優秀 [如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs /),之後你可能會知道你的問題的答案,甚至更好的是能夠找出未來類似問題的答案 – 2014-10-26 16:03:28

+0

@almasshaikh nope。沒有任何例外 – John 2014-10-26 16:10:53

回答

0

最有可能的原因是沒有得到的數據是,你有沒有正確設置文件的路徑。對於這一點,線下並不是必要的。

File file = new File(「example.txt」);

您可以從文件名中直接創建一個FileReader對象,如下所示。

的FileReader的FileReader =新的FileReader(「example.txt文件);

相關問題