从文本文件中创建Java列表

时间:2016-12-06 21:05:51

标签: java list file java.util.scanner

在Java中,我使用Scanner从文本文件中读取, 例如(猫,狗,老鼠)。 当我使用System.out.println()时,输出显示为cat, dog, mouse

我希望列表看起来像这样

cat
dog
mouse

以下任何帮助代码

    Scanner scan = null;
    Scanner scan2 = null;
    boolean same = true;
    try {
        scan = new Scanner(new      
        File("//home//mearts//keywords.txt"));
    } catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    List<String> firstLines = new ArrayList<String>();
    while (scan.hasNextLine()) {
    firstLines.add(scan.nextLine());
    System.out.println(firstLines);
}

2 个答案:

答案 0 :(得分:2)

尝试类似:

firstLines.forEach(System.out::println);

顺便说一下,由于您只是阅读线条,您可能还想查看java.nio.file.Files

Path keywordsFilepath = Paths.get(/* your path */...);
Files.lines(keywordsFilepath)
     .forEach(System.out::println);

答案 1 :(得分:2)

您正在逐行读取文件,而不是考虑分隔符:

try (Scanner scan = 
     new Scanner("//home//mearts//keywords.txt").useDelimiter(", ")) {
    while (scan.hasNext()) {
        System.out.println(scan.next());
    }
} catch (FileNotFoundException e) {
    e.printStackTrace(); // Or something more useful
}