有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

用Java从文本文件制作列表

在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) 个答案

  1. # 1 楼答案

    尝试以下方法:

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

    顺便说一句,由于您只阅读了几行,您可能还想看看java.nio.file.Files

    Path keywordsFilepath = Paths.get(/* your path */...);
    Files.lines(keywordsFilepath)
         .forEach(System.out::println);
    
  2. # 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
    }