You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java创建文件时遇FileNotFoundException未处理异常,求解决方案

Java文件操作报错:Unhandled exception type FileNotFoundException

报错原因

PrintWriter的构造方法会在以下场景抛出FileNotFoundException(属于Java检查型异常):

  • 指定的文件路径不存在(比如输入了带多级目录的路径,但目录未创建)
  • 程序没有该路径的写入权限
  • 文件名包含系统不允许的非法字符
    Java要求必须显式处理这类检查型异常,你的代码未做任何处理,因此编译器报错。

解决方法

方法1:捕获并处理异常(推荐)

用try-catch块包裹文件操作逻辑,捕获异常并给出友好提示,同时记得关闭文件确保内容写入:

import java.io.*;
import javax.swing.JOptionPane;

public class JavaFilePractice {        

    public static void main(String[] args){
        String filename = JOptionPane.showInputDialog("Enter the file name");
        
        try {
            PrintWriter outputFile = new PrintWriter(filename);
            outputFile.println("Jim");
            outputFile.close(); // 必须关闭文件,否则内容可能无法写入
        } catch (FileNotFoundException e) {
            JOptionPane.showMessageDialog(null, "文件操作失败:" + e.getMessage());
        }
    }
}

方法2:声明抛出异常(仅适合练习场景)

如果只是简单练习,不想编写异常处理逻辑,可以在main方法签名上声明抛出FileNotFoundException,将异常交给JVM处理(出现异常时程序会直接终止):

import java.io.*;
import javax.swing.JOptionPane;

public class JavaFilePractice {        

    public static void main(String[] args) throws FileNotFoundException{
        String filename = JOptionPane.showInputDialog("Enter the file name");
        PrintWriter outputFile = new PrintWriter(filename);
        
        outputFile.println("Jim");
        outputFile.close();
    }
}

内容的提问来源于stack exchange,提问作者wayne

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 15:06:07