【问题标题】:Getting file not found exception with PrintWriter and File使用 PrintWriter 和 File 获取文件未找到异常
【发布时间】:2020-10-25 21:22:50
【问题描述】:
public static void generateOutput() {
    File file = new File ("C:/Users/me/Desktop/file.txt");
    PrintWriter outputFile = null;
    outputFile = new PrintWriter(file);
}

上面是我的代码,我正在尝试制作一个 PrintWriter 来写入我在桌面上创建的名为 file.txt 的文件,但是我收到错误“未处理的异常类型,未找到文件的异常”。我查看了其他帖子,但不确定为什么我仍然收到此错误。我也试过在没有 File 对象的情况下这样做。我希望得到一些关于我哪里出错的指导

【问题讨论】:

  • 如果文件存在,则在方法签名中添加try-catch或抛出异常

标签: java file io output printwriter


【解决方案1】:

您必须在这里理解的最重要的想法是,您的文件可能:

  1. 找不到;
  2. 将其描述符锁定(这意味着其他进程正在使用它);
  3. 已损坏;
  4. 被写保护。

在上述所有情况下,触发 OS Kernel 的 Java 程序都会崩溃,并且异常将发生在 运行时。为了避免这种意外,Java 设计人员决定(他们做得很好)PrintWriter 应该抛出(意思是,有可能抛出)FileNotFoundException,这应该是编译时检查的异常。这样开发人员将避免更严重的运行时问题,例如程序崩溃。

因此,您必须:

  1. try-catch 在您的 PrintWriter 方法中;或
  2. 将异常向上抛出一级。

我想,你的问题是关于为什么会发生这种情况。这是两者的答案-(1)为什么? (2) 如何解决。

【讨论】:

    【解决方案2】:

    Java 有一个异常捕获机制,可以帮助您更好地编程。你将不得不处理一个异常FileNotFoundException 来警告如果程序找不到你的文件会发生什么或者你可以throws 这个异常。我建议学习 Java 中的异常处理。 这段代码可以帮助你

    public static void generateOutput() {
            File file = new File ("C:/Users/me/Desktop/file.txt");
            PrintWriter outputFile = null;
            try {
                outputFile = new PrintWriter(file);
            } catch (FileNotFoundException e) {
                // Handle if your file not found
                e.printStackTrace();
            }
        }
    

    或者

    public static void generateOutput() throws FileNotFoundException {
            File file = new File ("C:/Users/me/Desktop/file.txt");
            PrintWriter outputFile = null;
            outputFile = new PrintWriter(file);
        }
    

    【讨论】:

      【解决方案3】:

      假设您的文件存在于给定位置,您需要以下条件之一,

      public static void generateOutput() throws Exception {... Your code ...}

      或者

      try {
      //Your code 
      }
      catch(FileNotFoundException fnne) {
      // Precise exception catching example
      }
      catch(Exception e) {
      // Not required, but adding it to catch any other exception you might face
      }
      

      您始终可以在 throws/catch 中使用精确的异常。你需要它,因为PrintWriter 可以有编译时异常。基本上,这意味着如果找不到文件,那么它可以抛出异常并且在编译时就知道了。因此,您需要使用其中一种方法。

      除此之外,你将 2 行变成 1 如下,

      PrintWriter 输出 = new PrintWriter(file);

      你不需要将输出对象初​​始化为 null,除非你是故意的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-03-29
        • 2019-06-26
        相关资源
        最近更新 更多