【问题标题】:java PrintWriter cannot be resolvedjava PrintWriter 无法解决
【发布时间】:2014-03-20 23:11:53
【问题描述】:

我不知道为什么我在第 11 行的 eclipse 中收到“无法解决”的消息

import java.io.*;
public class driver {
public static void main(String[] args) {
    try {
           PrintWriter out = new PrintWriter("output.txt");
        }
    catch (FileNotFoundException e) {
        System.out.print("file not found");
        e.printStackTrace();
    }
    out.print("hello");
    out.close();
    }

}

好的,现在我有了这个

import java.io.*;
public class driver {
public static void main(String[] args) {
    PrintWriter out = null;
    try {
           out = new PrintWriter("output.txt");
        }
    catch (FileNotFoundException e) {
        System.out.print("file not found");
        e.printStackTrace();
    }
    out.print("hello");
    out.close();
  }
}

为什么我关闭后eclipse不创建文件?

【问题讨论】:

  • 答案是变量作用域,你应该把你的 close 移到 finally 块。如果遇到 FileNotFoundException,您希望输出到哪里?
  • @user3221287 文件没有被创建?
  • 请不要重复发布相同的问题。
  • 一个文件被创建。你只是不知道在哪里。试试绝对路径名看看。

标签: java printwriter


【解决方案1】:

try 块之前声明您的PrintWriter,使其范围不限于try 块。

【讨论】:

  • 非常感谢,希望您看看我所做的编辑,因为我不知道为什么程序结束后没有创建文件
【解决方案2】:

您也可以使用 JDK 1.7 中引入的新的 try-with-resource 块,这样做的好处是您无需担心关闭任何实现了可关闭接口的资源。

然后代码将如下所示:

try (PrintWriter out = new PrintWriter("output.txt"))
        {

            out.print("hello");
        }
        catch (FileNotFoundException e)
        {
            System.out.print("file not found");
            e.printStackTrace();
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-29
    • 2018-12-29
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多