• FileNotFoundException:FileOutputStream


    源码:

    /**
         * 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)
    欢迎关注Java流水账公众号
  • 相关阅读:
    Junit初级编码(一)第一个Junit测试程序
    关于健身与健美
    spring入门(一)
    HTTP状态301、404、200、304分别表示什么意思
    预处理prepareStatement是怎么防止sql注入漏洞的?
    详解SESSION与COOKIE的区别
    Form表单中method为get和post的区别
    tomcat服务器配置及使用
    ubuntu 14.04 安装mysql server初级教程
    《电路学习第三天》 之 线性稳压电源的设计
  • 原文地址:https://www.cnblogs.com/guofu-angela/p/9917381.html
Copyright © 2020-2023  润新知