我正在将文件内容读取到ArrayList,以便稍后可以处理数据。但是,当我尝试打印以进行控制台时,内容会反复显示。我在线上希望能够打印五行。如何调整代码,以便在控制台上显示时只能显示五行并重复显示结果?在文件中,我有
3456
1678
4354
2384
5634
阅读列表并显示为控制台后,结果为
3456
3456
1678
3456
1678
4354
3456
1678
4354
2384
3456
1678
4354
2384
5634
我只想显示五行。
3456
1678
4354
2384
5634
代码:
public void testread(){
System.out.println("Enter filename:\n");
String filename=Keyboard.readInput();
File myfile=new File(filename);
try (BufferedReader scanfile=new BufferedReader(new FileReader(myfile))) {
String str;
List<String>list=new ArrayList<String>();
while ((str=scanfile.readLine())!=null) {
int i;
list.add(str);
for (i=0; i<list.size(); i++) {
System.out.println(list.get(i));
}
}
} catch (IOException e) {
System.out.println("Error reading from file " + e.getMessage());
}
}
答案 0 :(得分:1)
您需要将for循环的打印内容从while循环中移出。 while循环的每次迭代都将打印列表中的每个值。像这样:
public void testread(){
System.out.println("Enter filename:\n");
String filename=Keyboard.readInput();
File myfile=new File(filename);
try(BufferedReader scanfile=new BufferedReader(new FileReader(myfile))){
String str;
List<String>
list=new ArrayList<String>();
while((str=scanfile.readLine())!=null)
{
int i;
list.add(str);
}
// then print the list
for(i=0;i<list.size();i++) {
System.out.println(list.get(i));
}
}catch (IOException e){
// Print error in case of failure.
System.out.println("Error reading from file " + e.getMessage());
}
}
答案 1 :(得分:0)
只需将for循环移到while循环之外即可。
public void testread(){
System.out.println("Enter filename:\n");
String filename=Keyboard.readInput();
File myfile=new File(filename);
try (BufferedReader scanfile=new BufferedReader(new FileReader(myfile))) {
String str;
List<String>list=new ArrayList<String>();
while ((str=scanfile.readLine())!=null) {
int i;
list.add(str);
}
for(i=0;i<list.size();i++) {
System.out.println(list.get(i));
}
} catch (IOException e) {
System.out.println("Error reading from file " + e.getMessage());
}
}