首页 > 解决方案 > Java,读取文件内容到arraylist

问题描述

我正在向 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());
    }
}

标签: java

解决方案


您需要将您的 print 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());
    }
}

推荐阅读