FileNotFoundException:FileOutputStream

本文详细解析了Java中FileOutputStream类的使用方法,包括如何处理文件不存在或无法创建的情况,以及如何在目录不存在时进行目录创建。同时,文章提供了具体的代码示例,展示了如何避免FileNotFoundException的抛出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

源码:

/**
     * Creates a file output stream to write to the file with the
     * specified name. A new <code>FileDescriptor</code> object is
     * created to represent this file connection.
     * <p>
     * First, if there is a security manager, its <code>checkWrite</code>
     * method is called with <code>name</code> as its argument.
     * <p>
     * If the file exists but is a directory rather than a regular file, does
     * not exist but cannot be created, or cannot be opened for any other
     * reason then a <code>FileNotFoundException</code> is thrown.
     *
     * @param      name   the system-dependent filename
     * @exception  FileNotFoundException  if the file exists but is a directory
     *                   rather than a regular file, does not exist but cannot
     *                   be created, or cannot be opened for any other reason
     * @exception  SecurityException  if a security manager exists and its
     *               <code>checkWrite</code> method denies write access
     *               to the file.
     * @see        java.lang.SecurityManager#checkWrite(java.lang.String)
     */
    public FileOutputStream(String name) throws FileNotFoundException {
        this(name != null ? new File(name) : null, false);
    }
  /**
     * Opens a file, with the specified name, for overwriting or appending.
     * @param name name of file to be opened
     * @param append whether the file is to be opened in append mode
     */
    private native void open0(String name, boolean append)
        throws FileNotFoundException;

注释说的很清楚,1.如果是个目录而不是具体文件;2.文件不存在但是不能被创建;3.因为其他原因不能被创建

解决方法:

1. 打开文件输出流之前先判断文件夹是否存在, 比如/www/data/test.json 是需要打开的文件,先判断/www/data/目录是否存在,如果目录不存在,创建目录。

2.文件夹创建之后,然后判断文件是否存在,不存在则创建空文件

File folder = new File(OUT_RESULT);
            if(!folder.exists()){  //打开文件输出流之前先判断文件夹是否存在
                boolean created = folder.mkdirs();
                if(!created){
                    //如果目录创建失败
                    logger.warn("File output folder created failure:" + OUT_RESULT);
                    throw new FileNotFoundException(OUT_RESULT);
                }
                File file = new File(outPath);
                if(!file.exists()){
                    file.createNewFile();
                }
            }

最后再打开文件流

new FileOutputStream(outPath)

 

转载于:https://www.cnblogs.com/zhengwangzw/p/9917381.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值