java - 使用Scanner读取文本文件并存储到ArrayList

标签 java file arraylist

我的任务是创建一个计算 Actor 培根数的程序。这是我给定的 ActorMovieTist.txt 文件的内容,应该在我的程序中读取该文件。

Adolf Hitler Der Ewige Jude 1940 
Angelina Jolie Mr. & Mrs. Smith 2005
Anne Hathaway Valentine's Day 2010
Benedict Cumberbatch The Hobbit: An unexpected Journey 2012
Benedict Cumberbatch Black Mass 2015
Brad Pitt Mr. & Mrs. Smith 2005
Brad Pitt Sleepers 1996
Brad Pitt Ocean's Thirteen 2007
Brad Pitt Beyond All Boundaries 2009
Brad Pitt Se7en 1995
Christian Bale The Fighter 2010
Curt Bois Der Ewige Jude 1940
Curt Bois The Great Sinner 1949
Denzel Washington 2 Guns 2013
Denzel Washington The Equalizer 2014
David Struffolino The Equalizer 2014
David Struffolino Knight and Day 2010
Hugh Jackman Flushed Away 2006
Hugh Jackman X Men First Class 2011
Ian McKellen The Hobbit: An unexpected Journey 2012
Julia Roberts Valentine's Day 2010
Julia Roberts Flatliners 1990
Kate Winslet Flushed Away 2006
Kenneth Tobey The Great Sinner 1949
Kenneth Tobey Hero at Large 1980
Kevin Bacon Sleepers 1996
Kevin Bacon Beyond All Boundaries 2009
Kevin Bacon Flatliners 1990
Kevin Bacon Patriots Day 2016
Kevin Bacon Black Mass 2015
Kevin Bacon X Men First Class 2011
Kevin Bacon Hero at Large 1980
Kevin Spacey Se7en 1995
Kevin Spacey Patriots Day 2016
Kevin Spacey Austin Powers in Goldmember 2002
Mark Wahlberg 2 Guns 2013
Mark Wahlberg Patriots Day 2016
Mark Wahlberg The Fighter 2010
Matt Damon Ocean's Thirteen 2007
Tom Cruise Austin Powers in Goldmember 2002

这是我的程序,它应该使用 Scanner 来读取此文件并将每一行保存为 ArrayList 的元素,但事实并非如此。我在最后打印了 ArrayList 的大小,但我的程序一直显示 0。我做错了什么?

import java.util.*;
import java.io.File;
import java.io.IOException;



public class KevinBacon
{
    public static void main(String args[]) throws Exception{ 
        Formatter output = new Formatter("ActorMovieList.txt");
        File file = new File("ActorMovieList.txt");
        Scanner input = new Scanner(file);
        String line = "";

    ArrayList <String> list = new ArrayList <String>(); 

    while (input.hasNextLine()) {
        list.add(input.nextLine());
    }

    System.out.println(list.size());
}

}

最佳答案

这样做时您将覆盖输入文件

Formatter output = new Formatter("ActorMovieList.txt");

如果文件存在,那么它将被截断为零大小;否则,将创建一个新文件

因为您似乎没有使用此输出对象,只需删除此行并重新创建您的输入文件即可。

关于java - 使用Scanner读取文本文件并存储到ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53254737/

相关文章:

Java Arraylist 删除对象

java - Android:如何永久保存变量?

c - 如何在 while 循环中打开依赖于尚未声明的信息的文件?

c - 想要填充元数据结构

java - 如何迭代对象的数组列表以查找指定的对象

java - 将数组列表分成固定大小的子列表

java - Crontab 无法运行 jar 文件

java - azure应用程序服务上的spring boot应用程序在启动后立即停止

java - NoSuchMethodError : com. google.common.base.Platform.systemNanoTime() 在 GWT 项目中

javascript - 如何使用异步回调响应返回文件内容?