【问题标题】:Java 8 file I/O NoSuchElementException: no line foundJava 8 文件 I/O NoSuchElementException:找不到行
【发布时间】:2018-06-19 10:44:23
【问题描述】:

我的目标是读取格式化字符串并将其写入文件。 我实际上使用 PrintWriter 类进行输出,使用 Scanner 类进行输入。

代码:

        PrintWriter out = null;
        Scanner in = null;
        File file = new File(System.getProperty("user.dir")+"/data/level1/grounds.txt");
        try {
            out = new PrintWriter(file);
        } catch (FileNotFoundException e) { e.printStackTrace(); }

        out.println("foo");

        try {
            in = new Scanner(file);
        } catch (FileNotFoundException e) { e.printStackTrace(); }

        System.out.println(in.nextLine());
        in.close();

文件已创建,但 in.nextLine() 抛出 NoSuchElementException: no line found。 执行后(由此异常终止)文件为空白。

请留下关于如何正确执行的建议。

【问题讨论】:

  • 顺便说一句,您使用的是 Java 8,您确实应该避免使用 File 并改用 Path 以及 java.nio 包中的所有相关方法。此外,如果找不到文件,则不应输出到文件。打印应该在try 内。完成后,您应该使用“try-with-resources”自动关闭文件。

标签: java string io java.util.scanner printwriter


【解决方案1】:

完成所有写入后,您应该关闭输出打印机以使其反映在扫描仪中。

【讨论】:

  • 哦,我错过了这么明显的事情。感谢您的建议。
【解决方案2】:

这是因为out.println("foo");写入PrintWriter而不是文件上,你需要flush()才能有文件上的内容,你也可以close()(这会自动flush()

  1. 简单冲洗

    out.println("foo"); 
    out.flush()
    
  2. 接近冲洗

    out.println("foo"); 
    out.close()
    
  3. 使用自动刷新的 PrintWriter

    out = new PrintWriter(new FileOutputStream(file), true);
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 1970-01-01
    • 2016-02-09
    相关资源
    最近更新 更多