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

相关文章

Nginx安全防护的多种方法

《Nginx安全防护的多种方法》在生产环境中,需要隐藏Nginx的版本号,以避免泄漏Nginx的版本,使攻击者不能针对特定版本进行攻击,下面就来介绍一下Nginx安全防护的方法,感兴趣的可以了解一下... 目录核心安全配置1.编译安装 Nginx2.隐藏版本号3.限制危险请求方法4.请求限制(CC攻击防御)

python生成随机唯一id的几种实现方法

《python生成随机唯一id的几种实现方法》在Python中生成随机唯一ID有多种方法,根据不同的需求场景可以选择最适合的方案,文中通过示例代码介绍的非常详细,需要的朋友们下面随着小编来一起学习学习... 目录方法 1:使用 UUID 模块(推荐)方法 2:使用 Secrets 模块(安全敏感场景)方法

MyBatis-Plus通用中等、大量数据分批查询和处理方法

《MyBatis-Plus通用中等、大量数据分批查询和处理方法》文章介绍MyBatis-Plus分页查询处理,通过函数式接口与Lambda表达式实现通用逻辑,方法抽象但功能强大,建议扩展分批处理及流式... 目录函数式接口获取分页数据接口数据处理接口通用逻辑工具类使用方法简单查询自定义查询方法总结函数式接口

MySQL深分页进行性能优化的常见方法

《MySQL深分页进行性能优化的常见方法》在Web应用中,分页查询是数据库操作中的常见需求,然而,在面对大型数据集时,深分页(deeppagination)却成为了性能优化的一个挑战,在本文中,我们将... 目录引言:深分页,真的只是“翻页慢”那么简单吗?一、背景介绍二、深分页的性能问题三、业务场景分析四、

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Java中读取YAML文件配置信息常见问题及解决方法

《Java中读取YAML文件配置信息常见问题及解决方法》:本文主要介绍Java中读取YAML文件配置信息常见问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要... 目录1 使用Spring Boot的@ConfigurationProperties2. 使用@Valu

Java 方法重载Overload常见误区及注意事项

《Java方法重载Overload常见误区及注意事项》Java方法重载允许同一类中同名方法通过参数类型、数量、顺序差异实现功能扩展,提升代码灵活性,核心条件为参数列表不同,不涉及返回类型、访问修饰符... 目录Java 方法重载(Overload)详解一、方法重载的核心条件二、构成方法重载的具体情况三、不构

SQL中如何添加数据(常见方法及示例)

《SQL中如何添加数据(常见方法及示例)》SQL全称为StructuredQueryLanguage,是一种用于管理关系数据库的标准编程语言,下面给大家介绍SQL中如何添加数据,感兴趣的朋友一起看看吧... 目录在mysql中,有多种方法可以添加数据。以下是一些常见的方法及其示例。1. 使用INSERT I

Python中反转字符串的常见方法小结

《Python中反转字符串的常见方法小结》在Python中,字符串对象没有内置的反转方法,然而,在实际开发中,我们经常会遇到需要反转字符串的场景,比如处理回文字符串、文本加密等,因此,掌握如何在Pyt... 目录python中反转字符串的方法技术背景实现步骤1. 使用切片2. 使用 reversed() 函

Python中将嵌套列表扁平化的多种实现方法

《Python中将嵌套列表扁平化的多种实现方法》在Python编程中,我们常常会遇到需要将嵌套列表(即列表中包含列表)转换为一个一维的扁平列表的需求,本文将给大家介绍了多种实现这一目标的方法,需要的朋... 目录python中将嵌套列表扁平化的方法技术背景实现步骤1. 使用嵌套列表推导式2. 使用itert