如何增加while循环以读取文件的下一行

时间:2015-10-21 23:24:47

标签: java arraylist while-loop bufferedreader

我正在编写代码 首先)询问用户文件名 秒)读取文件并将每一行放入ArrayList 第三个)打印出ArrayList

我的代码是使用BufferedReader读取文件,但它只打印出第一行25次而不是打印出25行不同。

这就是我的while循环的样子。我不知道如何增加它

ArrayList<String> stringArray = new ArrayList<String>();
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(fileName));

String line = reader.readLine();
while(reader.readLine() != null){
    stringArray.add(line);
}
return stringArray;

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您不是在每次运行时读取变量的行,您需要在while循环中读取它。

String line = reader.readLine();
while(line != null){
    stringArray.add(line);
    line = reader.readLine(); // read the next line
}
return stringArray;

答案 1 :(得分:0)

这不是首选解决方案。只是表明它可以以不同的方式完成

或者你可以使用do ...而不是while ... do。

String line;
do {
    line = reader.readLine();
    if (line != null) {
       stringArray.add(line);
    }
} while (line != null);

您可以看到为什么这不是首选解决方案。你正在进行2次空检查,你可以逃避1。

答案 2 :(得分:0)

 while (true) {
    String line = reader.readLine(); 
    if (line == null) break;
    stringArray.add(line);
 }
 return stringArray;