本帖最后由 toShareBeauty 于 2013-7-9 21:30 编辑
这个要从 java 的 File 说起,- /**
- * Atomically creates a new, empty file named by this abstract pathname if
- * and only if a file with this name does not yet exist. The check for the
- * existence of the file and the creation of the file if it does not exist
- * are a single operation that is atomic with respect to all other
- * filesystem activities that might affect the file.
- * <P>
- * Note: this method should <i>not</i> be used for file-locking, as
- * the resulting protocol cannot be made to work reliably. The
- * {@link java.nio.channels.FileLock FileLock}
- * facility should be used instead.
- *
- * @return <code>true</code> if the named file does not exist and was
- * successfully created; <code>false</code> if the named file
- * already exists
- *
- * @throws IOException
- * If an I/O error occurred
- *
- * @throws SecurityException
- * If a security manager exists and its <code>{@link
- * java.lang.SecurityManager#checkWrite(java.lang.String)}</code>
- * method denies write access to the file
- *
- * @since 1.2
- */
- public boolean createNewFile() throws IOException {
- SecurityManager security = System.getSecurityManager();
- if (security != null) security.checkWrite(path);
- return fs.createFileExclusively(path);
- }
复制代码 上面是 File 源文件的 createNewFile() 函数,return fs.createFileExclusively(path); 中的 fs 是类 FileSystem 的对象,- /**
- * Create a new empty file with the given pathname. Return
- * <code>true</code> if the file was created and <code>false</code> if a
- * file or directory with the given pathname already exists. Throw an
- * IOException if an I/O error occurs.
- */
- public abstract boolean createFileExclusively(String pathname)
- throws IOException;
复制代码 这是 FileSystem.java 中的 createFileExclusively(String pathname) 函数,这个 FileSystem 是个 JNI ,也就是 java 本地扩展,它的实现使用 c/c++ 调用系统api或者函数库实现的。看到上面的注释了么,
“Return <code>true</code> if the file was created and <code>false</code> if a file or directory with the given pathname already exists. ”
java 的 createNewFile 的时候会检查 File 表示的文件夹或者文件是否存在,如果其中一个存在就不会创建啦。同理,mkdir 的源码也可以这样分析。
|