`

File 类源代码解析

阅读更多
1. 分隔符

    // 名称分隔符,Windows系统为反斜杠'\\',Linux系统为斜杠'/'
    public static final char separatorChar = fs.getSeparator();

    // 名称分隔字符串
    public static final String separator = "" + separatorChar;

    // 路径分隔符,Windows系统为分号';',Linux系统为冒号':'
    public static final char pathSeparatorChar = fs.getPathSeparator();

    // 路径分隔字符串
    public static final String pathSeparator = "" + pathSeparatorChar;


2. 文件路径
    // 标准的符号完全解析的绝对路径,具有唯一性,去除了绝对路径中可能存在的..或.,符号链接(Linux),标准化盘符字母大小写。
    public String getCanonicalPath() throws IOException {
        return fs.canonicalize(fs.resolve(this));
    }

    // 文件的绝对路径
    public String getAbsolutePath() {
        return fs.resolve(this);
    }

    // ile构造方法里的路径,可以是相对或绝对路径
    public String getPath() {
        return path;
    }

    // 父路径
    public String getParent() {
        int index = path.lastIndexOf(separatorChar); // 最后一个名称分隔符位置
        if (index < prefixLength) {
            if ((prefixLength > 0) && (path.length() > prefixLength))
                return path.substring(0, prefixLength); // 返回前缀
            return null;
        }
        return path.substring(0, index); // 返回分隔符之前的字符串
    }

    // 文件名称
    public String getName() {
        int index = path.lastIndexOf(separatorChar);
        if (index < prefixLength) return path.substring(prefixLength);
        return path.substring(index + 1);
    }


测试:
    System.out.println(System.getProperty("user.dir"));
    
    System.out.println("-----Relative path: different return paths-----");
    File file1 = new File("..\\src\\test1.txt");
    System.out.println(file1.getPath());
    System.out.println(file1.getAbsolutePath());
    System.out.println(file1.getCanonicalPath());
    
    System.out.println("-----Relative path: different return paths-----");
    File file2 = new File(".\\test1.txt");
    System.out.println(file2.getPath());
    System.out.println(file2.getAbsolutePath());
    System.out.println(file2.getCanonicalPath());
    
    System.out.println("-----Absolute path: the same return paths-----");
    File file3 = new File("D:\\workspace\\perfume\\src\\test1.txt");
    System.out.println(file3.getPath());
    System.out.println(file3.getAbsolutePath());
    System.out.println(file3.getCanonicalPath());


输出:
D:\workspace\perfume
-----Relative path: different return paths-----
..\src\test1.txt
D:\workspace\perfume\..\src\test1.txt
D:\workspace\src\test1.txt
-----Relative path: different return paths-----
.\test1.txt
D:\workspace\perfume\.\test1.txt
D:\workspace\perfume\test1.txt
-----Absolute path: the same return paths-----
D:\workspace\perfume\src\test1.txt
D:\workspace\perfume\src\test1.txt
D:\workspace\perfume\src\test1.txt

3. 文件属性
    // 是否可读
    public boolean canRead() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(path);
        }
        return fs.checkAccess(this, FileSystem.ACCESS_READ);
    }

    // 是否可写
    public boolean canWrite() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite(path);
        }
        return fs.checkAccess(this, FileSystem.ACCESS_WRITE);
    }

    // 文件是否存在
    public boolean exists() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(path);
        }
        return ((fs.getBooleanAttributes(this) & FileSystem.BA_EXISTS) != 0);
    }

    // 是否是目录
    public boolean isDirectory() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(path);
        }
        return ((fs.getBooleanAttributes(this) & FileSystem.BA_DIRECTORY)
                != 0);
    }

    // 是否是文件
    public boolean isFile() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(path);
        }
        return ((fs.getBooleanAttributes(this) & FileSystem.BA_REGULAR) != 0);
    }

    // 是否隐藏
    public boolean isHidden() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(path);
        }
        return ((fs.getBooleanAttributes(this) & FileSystem.BA_HIDDEN) != 0);
    }

    // 最近访问时间
    public long lastModified() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(path);
        }
        return fs.getLastModifiedTime(this);
    }

    // 文件长度,如果是目录,返回值未指定
    public long length() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(path);
        }
        return fs.getLength(this);
    }


4. 文件操作
    // 创建文件
    public boolean createNewFile() throws IOException {
        SecurityManager security = System.getSecurityManager();
        if (security != null) security.checkWrite(path);
        return fs.createFileExclusively(path);
    }

    // 删除文件
    public boolean delete() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkDelete(path);
        }
        return fs.delete(this);
    }

    // 在虚拟机正常终止的时候删除文件,删除文件的顺序和注册的时候相反,已经注册过的再次调用此方法没有影响
    public void deleteOnExit() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkDelete(path);
        }
        DeleteOnExitHook.add(path);
    }

    // 获取当前路径所代表的目录下的文件和目录列表,如果不是目录,返回null。
    // 返回的字符串是文件名,不是完整路径。
    // 列表根据alphabetical来排序。
    public String[] list() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkRead(path);
        }
        return fs.list(this);
    }

    // 同上,加了个文件名称过滤
    public String[] list(FilenameFilter filter) {
        String names[] = list();
        if ((names == null) || (filter == null)) {
            return names;
        }
        List<String> v = new ArrayList<>();
        for (int i = 0 ; i < names.length ; i++) {
            if (filter.accept(this, names[i])) {
                v.add(names[i]);
            }
        }
        return v.toArray(new String[v.size()]);
    }

    // 同上,将路径名转换为文件
    public File[] listFiles() {
        String[] ss = list();
        if (ss == null) return null;
        int n = ss.length;
        File[] fs = new File[n];
        for (int i = 0; i < n; i++) {
            fs[i] = new File(ss[i], this); // 根据路径实例化文件对象
        }
        return fs;
    }

    // 创建目录,如果父目录不存在,抛异常
    public boolean mkdir() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite(path);
        }
        return fs.createDirectory(this);
    }

    // 创建目录,如果父目录不存在,先创建父目录
    public boolean mkdirs() {
        if (exists()) {
            return false;
        }
        if (mkdir()) {
            return true;
        }
        File canonFile = null;
        try {
            canonFile = getCanonicalFile();
        } catch (IOException e) {
            return false;
        }

        File parent = canonFile.getParentFile();
        return (parent != null && (parent.mkdirs() || parent.exists()) &&
        canonFile.mkdir()); // 当且仅当父目录不为null,父目录创建成功或存在,当前目录创建成功时返回true
    }

    // 重命名文件
    public boolean renameTo(File dest) {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite(path);
            security.checkWrite(dest.path);
        }
        return fs.rename(this, dest);
    }


设置属性

    // 设置文件为只读,直到设置为允许写或删除
    public boolean setReadOnly() {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkWrite(path);
        }
        return fs.setReadOnly(this);
    }


某些设置可能不起作用,如在Windows平台上,setReadable(false),文件的canRead()还是true:
    String fileName = "D:/spark.txt";
    File file = new File(fileName);
    System.out.println("canRead: " + file.canRead());
    System.out.println("canWrite: " + file.canWrite());
    System.out.println("canExecute: " + file.canExecute());
    System.out.println("-----After changing-----");
    file.setReadable(false); // It doesn't take effect on Windows platform
    System.out.println("canRead: " + file.canRead());
    file.setWritable(false);
    System.out.println("canWrite: " + file.canWrite());
    file.setExecutable(false); // It doesn't take effect on Windows platform
    System.out.println("canExecute: " + file.canExecute());


输出:
canRead: true
canWrite: true
canExecute: true
-----After changing-----
canRead: true
canWrite: false
canExecute: true
分享到:
评论

相关推荐

    FileMonitor 文件监控源代码

    分析FileMonitor的源代码,我们可以学习如何使用Windows API进行文件监控,了解如何处理文件系统事件,以及如何在多线程环境下保证程序的正确运行。这对于系统管理员进行故障排查,或者开发者实现自定义的日志系统...

    linux file 命令源代码

    1. **文件结构与功能划分**:`file`命令的源代码通常会按照功能模块进行组织,例如解析二进制数据的函数、处理文本文件的部分、处理MIME类型的部分等。通过查看源代码目录,我们可以找到这些功能对应的源文件,如`...

    C++编写的SearchFile程序源代码

    本篇将详细解析"SearchFile"程序源代码的相关知识点,帮助你理解C++如何实现文件检索功能。 首先,C++中的文件操作是通过标准库提供的`fstream`头文件实现的,包含`ifstream`(输入文件流)和`ofstream`(输出文件...

    linux file 命令的源代码

    分析`file`命令的源代码可以帮助我们了解其内部工作原理,包括如何处理二进制数据、如何解析配置文件、如何进行性能优化等。这对于开发类似工具或需要定制`file`命令行为的用户来说非常有价值。同时,源代码学习也是...

    structual-file parser 源代码

    "Structural File Parser"是一个用于解析结构化文件的工具,其源代码的分析将带我们深入理解文件解析的原理和实现。在这个项目中,我们有三个主要的资源:一篇相关的博客文章、一个PPT演示文稿和源代码本身。下面...

    yaffs2源代码情景分析 -.rar

    《深入解析YAFFS2源代码:一场编程的探索之旅》 YAFFS2,全称为Yet Another Flash File System 2,是专为嵌入式系统设计的一种日志型文件系统,尤其适用于 NAND 闪存。它在嵌入式设备领域有着广泛的应用,尤其是在...

    Linux内核源代码分析 附赠光盘

    Linux内核源代码分析 附赠光盘 原书名:Linux Core Kernel Commentary 原出版社: ITP 作者: Scott Maxwell Linux Core Kernel Commentary Readme linux-0.01 The original Linux kernel distribution, dating ...

    java常用类解析及示例及一些工具类源代码

    这是java常用类解析系列博客中的示例代码及自己写的工具类,代码注释详细,博客地址:http://blog.csdn.net/touch_2011/article/details/6860043 主要讲解了System类、Object类、Arrays类、Cloneable接口、IO系统...

    深入云计算 Hadoop源代码分析

    ### 深入云计算 Hadoop源代码分析 #### 一、引言 随着大数据时代的到来,数据处理成为了各个领域中的关键技术之一。Hadoop作为一个开源的大数据处理框架,因其优秀的分布式计算能力,在业界得到了广泛的应用。...

    ftp源代码2ftp源代码ftp2源代码ftp2源代码2

    FTP源代码是指实现FTP协议的程序代码,通常用于开发自己的FTP客户端或服务器软件。这些源代码可以是开源的,也可以是私有的。开源FTP源代码为开发者提供了研究和自定义FTP功能的机会,以便满足特定需求或改进现有...

    FTPFILE FTP-FTP源代码分享

    源代码分析是学习任何软件系统的基础,FTPFILE FTP-FTP源代码可以帮助我们了解FTP协议的实际工作原理和实现细节。以下是基于FTP源代码的一些关键知识点: 1. **连接与身份验证**:FTP协议通常使用两个端口——21号...

    Apache Server源代码分析

    本篇将围绕"Apache Server源代码分析"这一主题,详细介绍Apache服务器的核心概念、架构设计以及关键模块。 Apache服务器的源代码结构主要分为以下几个部分: 1. **主程序(Main Program)**:Apache服务器的启动点...

    PORTMON File Moniter4.34.rar源代码

    标题中的"PORTMON File Moniter4.34.rar源代码"指的是一个名为PORTMON的文件监控工具的4.34版本源代码,被压缩在名为"File Moniter4.34.rar"的RAR文件中。这个工具通常用于监控系统中的文件活动,如打开、关闭、读取...

    unix 源代码分析

    文件系统(file system)是Unix的重要特性,其源代码展示了如何组织和操作磁盘上的数据。Unix采用树形目录结构,每个文件都有唯一的路径名,这在源代码中体现为文件系统相关的系统调用,如open、read、write等。同时...

    WEKA的源代码分析

    然后,在Eclipse中选择"File" -&gt; "Import" -&gt; "Existing Projects into Workspace",浏览找到WEKA的源代码目录,按照向导步骤导入项目。 **3. 编译与运行WEKA** 在Eclipse中,我们可以直接编译和运行WEKA的源代码...

    Hadoop源代码分析(一)

    Hadoop的源代码分析可以从以下几个关键点开始: 1. **HDFS架构**:HDFS是一个分布式文件系统,设计用于在廉价硬件上运行。它的核心思想是数据本地化,即数据应该存储在处理它的节点附近,以提高效率。HDFS中的主要...

    编译原理词法分析 简单词法分析源代码

    7. **结束标记**:词法分析器还需要一个特殊的记号表示源代码的结束,这通常是一个EOF(End Of File)记号。 在进行词法分析时,开发者还需要考虑一些细节问题,比如是否区分大小写、如何处理多行注释、如何处理...

    PE文件分析器WinDump的Delphi源代码..rar

    本篇将深入探讨一个名为WinDump的PE(Portable Executable)文件分析器的Delphi源代码,通过解析这个项目,我们可以深入了解Delphi编程技巧以及PE文件格式。 首先,让我们了解PE文件格式。PE是Windows操作系统中的...

    C# FileWatcher文件监控系统源代码

    总的来说,`FileWatchUpdate`这个C#源代码项目提供了一个实用的工具,可以帮助开发者或系统管理员实时监控指定目录下的文件系统变化,并记录这些变化,以便后续分析或自动化流程。通过深入理解`FileSystemWatcher`的...

Global site tag (gtag.js) - Google Analytics