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流水账公众号