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

2024-06-21 10:18

本文主要是介绍File I/O source code--新建文件 相关方法阅读,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

虽然我们经常在用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);

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

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

/* A normal Unix pathname contains no duplicate slashes and does not end59          with a slash.  It may be the empty string. */60   61       /* Normalize the given pathname, whose length is len, starting at the given62          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 real81          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初涉




这篇关于File I/O source code--新建文件 相关方法阅读的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1080949

相关文章

macOS无效Launchpad图标轻松删除的4 种实用方法

《macOS无效Launchpad图标轻松删除的4种实用方法》mac中不在appstore上下载的应用经常在删除后它的图标还残留在launchpad中,并且长按图标也不会出现删除符号,下面解决这个问... 在 MACOS 上,Launchpad(也就是「启动台」)是一个便捷的 App 启动工具。但有时候,应

SpringBoot日志配置SLF4J和Logback的方法实现

《SpringBoot日志配置SLF4J和Logback的方法实现》日志记录是不可或缺的一部分,本文主要介绍了SpringBoot日志配置SLF4J和Logback的方法实现,文中通过示例代码介绍的非... 目录一、前言二、案例一:初识日志三、案例二:使用Lombok输出日志四、案例三:配置Logback一

Python实现无痛修改第三方库源码的方法详解

《Python实现无痛修改第三方库源码的方法详解》很多时候,我们下载的第三方库是不会有需求不满足的情况,但也有极少的情况,第三方库没有兼顾到需求,本文将介绍几个修改源码的操作,大家可以根据需求进行选择... 目录需求不符合模拟示例 1. 修改源文件2. 继承修改3. 猴子补丁4. 追踪局部变量需求不符合很

在java中如何将inputStream对象转换为File对象(不生成本地文件)

《在java中如何将inputStream对象转换为File对象(不生成本地文件)》:本文主要介绍在java中如何将inputStream对象转换为File对象(不生成本地文件),具有很好的参考价... 目录需求说明问题解决总结需求说明在后端中通过POI生成Excel文件流,将输出流(outputStre

mysql出现ERROR 2003 (HY000): Can‘t connect to MySQL server on ‘localhost‘ (10061)的解决方法

《mysql出现ERROR2003(HY000):Can‘tconnecttoMySQLserveron‘localhost‘(10061)的解决方法》本文主要介绍了mysql出现... 目录前言:第一步:第二步:第三步:总结:前言:当你想通过命令窗口想打开mysql时候发现提http://www.cpp

Mysql删除几亿条数据表中的部分数据的方法实现

《Mysql删除几亿条数据表中的部分数据的方法实现》在MySQL中删除一个大表中的数据时,需要特别注意操作的性能和对系统的影响,本文主要介绍了Mysql删除几亿条数据表中的部分数据的方法实现,具有一定... 目录1、需求2、方案1. 使用 DELETE 语句分批删除2. 使用 INPLACE ALTER T

MySQL INSERT语句实现当记录不存在时插入的几种方法

《MySQLINSERT语句实现当记录不存在时插入的几种方法》MySQL的INSERT语句是用于向数据库表中插入新记录的关键命令,下面:本文主要介绍MySQLINSERT语句实现当记录不存在时... 目录使用 INSERT IGNORE使用 ON DUPLICATE KEY UPDATE使用 REPLACE

PyCharm如何设置新建文件默认为LF换行符

《PyCharm如何设置新建文件默认为LF换行符》:本文主要介绍PyCharm如何设置新建文件默认为LF换行符问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录PyCharm设置新建文件默认为LF换行符设置换行符修改换行符总结PyCharm设置新建文件默认为LF

JavaScript Array.from及其相关用法详解(示例演示)

《JavaScriptArray.from及其相关用法详解(示例演示)》Array.from方法是ES6引入的一个静态方法,用于从类数组对象或可迭代对象创建一个新的数组实例,本文将详细介绍Array... 目录一、Array.from 方法概述1. 方法介绍2. 示例演示二、结合实际场景的使用1. 初始化二

CentOS 7部署主域名服务器 DNS的方法

《CentOS7部署主域名服务器DNS的方法》文章详细介绍了在CentOS7上部署主域名服务器DNS的步骤,包括安装BIND服务、配置DNS服务、添加域名区域、创建区域文件、配置反向解析、检查配置... 目录1. 安装 BIND 服务和工具2.  配置 BIND 服务3 . 添加你的域名区域配置4.创建区域