【问题标题】:Making a List in Java from a text file从文本文件用 Java 制作列表
【发布时间】:2016-12-06 21:05:51
【问题描述】:

在 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);
}

【问题讨论】:

标签: java list file java.util.scanner


【解决方案1】:

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

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
}

【讨论】:

    【解决方案2】:

    尝试类似:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-17
      • 1970-01-01
      • 1970-01-01
      • 2012-04-26
      • 1970-01-01
      • 2017-04-22
      • 2022-11-27
      • 2013-07-27
      相关资源
      最近更新 更多