如何增加 while 循环以读取文件的下一行
How to increment a while loop to read the next line on a file
我正在编写代码
first) 询问用户文件名
second) 读取文件并将每一行放入 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;
有什么想法吗?
您不是在每个 运行 上读取变量的行,您需要在 while 循环中读取它。
String line = reader.readLine();
while(line != null){
stringArray.add(line);
line = reader.readLine(); // read the next line
}
return stringArray;
这不是首选解决方案。只是表明它可以用不同的方式完成
或者您可以使用 do...while 而不是 while...do。
String line;
do {
line = reader.readLine();
if (line != null) {
stringArray.add(line);
}
} while (line != null);
您会明白为什么这不是首选解决方案。您正在进行 2 次空检查,您可以在其中进行 1 次检查。
while (true) {
String line = reader.readLine();
if (line == null) break;
stringArray.add(line);
}
return stringArray;
我正在编写代码 first) 询问用户文件名 second) 读取文件并将每一行放入 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;
有什么想法吗?
您不是在每个 运行 上读取变量的行,您需要在 while 循环中读取它。
String line = reader.readLine();
while(line != null){
stringArray.add(line);
line = reader.readLine(); // read the next line
}
return stringArray;
这不是首选解决方案。只是表明它可以用不同的方式完成
或者您可以使用 do...while 而不是 while...do。
String line;
do {
line = reader.readLine();
if (line != null) {
stringArray.add(line);
}
} while (line != null);
您会明白为什么这不是首选解决方案。您正在进行 2 次空检查,您可以在其中进行 1 次检查。
while (true) {
String line = reader.readLine();
if (line == null) break;
stringArray.add(line);
}
return stringArray;