File I/O source code--新建文件 相关方法阅读

来源:互联网 发布:编程的基础知识 编辑:程序博客网 时间:2024/06/15 11:13

虽然我们经常在用java的I/O,但是我们有没有想过,我们是怎样来创建文件的呢

首先我们来新建一个文件:

try {       File file = new File("c:\\newfile.txt");       if (file.createNewFile()){        System.out.println("File is created!");      }else{        System.out.println("File already exists.");      }     } catch (Exception e) {      e.printStackTrace();}

我们的目的是在c盘根目录新建一个名称为newfile.txt的文件,我们看看File的构造方法是如何写的呢

/**     * Creates a new <code>File</code> instance by converting the given     * pathname string into an abstract pathname.  If the given string is     * the empty string, then the result is the empty abstract pathname.     *     * @param   pathname  A pathname string     * @throws  NullPointerException     *          If the <code>pathname</code> argument is <code>null</code>     */    public File(String pathname) {        if (pathname == null) {            throw new NullPointerException();        }        this.path = fs.normalize(pathname);        this.prefixLength = fs.prefixLength(this.path);    }

这里的fs对象是这么来的

/**     * The FileSystem object representing the platform's local file system.     */    static private FileSystem fs = FileSystem.getFileSystem();

然后我们进入FileSystem类中发现,normalize(...)为抽象方法:

 /**     * Convert the given pathname string to normal form.  If the string is     * already in normal form then it is simply returned.     */    public abstract String normalize(String path);

所以我们可以看出,一定有相关的实现方法,我找了很久发现他有三个子类分别为:  UnixFileSystemWinNTFileSystemWin32FileSystem

我们先看UnixFileSystem 中是如何实现的

/* A normal Unix pathname contains no duplicate slashes and does not end   59          with a slash.  It may be the empty string. */   60      61       /* Normalize the given pathname, whose length is len, starting at the given   62          offset; everything before this offset is already normal. */   63       private String normalize(String pathname, int len, int off) {   64           if (len == 0) return pathname;   65           int n = len;   66           while ((n > 0) && (pathname.charAt(n - 1) == '/')) n--;   67           if (n == 0) return "/";   68           StringBuffer sb = new StringBuffer(pathname.length());   69           if (off > 0) sb.append(pathname.substring(0, off));   70           char prevChar = 0;   71           for (int i = off; i < n; i++) {   72               char c = pathname.charAt(i);   73               if ((prevChar == '/') && (c == '/')) continue;   74               sb.append(c);   75               prevChar = c;   76           }   77           return sb.toString();   78       }   79      80       /* Check that the given pathname is normal.  If not, invoke the real   81          normalizer on the part of the pathname that requires normalization.   82          This way we iterate through the whole pathname string only once. */   83       public String normalize(String pathname) {   84           int n = pathname.length();   85           char prevChar = 0;   86           for (int i = 0; i < n; i++) {   87               char c = pathname.charAt(i);   88               if ((prevChar == '/') && (c == '/'))   89                   return normalize(pathname, n, i - 1);   90               prevChar = c;   91           }   92           if (prevChar == '/') return normalize(pathname, n, n - 1);   93           return pathname;   94       }

大致的意思就是判断字符串中是否含有‘/’符号(是否是相对路径),如果pathname中包含有多个反斜杠(/),根据源码分析最终得出的只会返回一个反斜杠

我们接着往下看:

/**     * Compute the length of this pathname string's prefix.  The pathname     * string must be in normal form.     */    public abstract int prefixLength(String path);

它的实现方法是:

public int prefixLength(String pathname) {if (pathname.length() == 0)return 0;return (pathname.charAt(0) == '/') ? 1 : 0;}

这个看完之后我们再来看看它到底是如何来创建文件的呢

/**     * 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);    }

这里关键是fs.createFileExclusively(path),进去看了之后发现它是一个抽象方法

我们看下这里的描述Return ture if the file was created and false if a file or directory with the given pathname already exists。

它的意思是如果文件创建成功则返回true,如果文件或路径已经创建则返回false

/**     * 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;

实现类中方法却是本地方法

public native boolean createFileExclusively(String path)             throws IOException;

那什么是java native方法呢?

英文不太好,看了半天没搞球太明白,后来看到一篇中文的描述感觉挺好的,所以这里感谢分享的朋友

详细连接:java Native Method初涉




0 0
原创粉丝点击