2014-10-26 103 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文件);

相关问题