Groovy - 文件属性
Groovy 提供了 File class,它提供了多个属性和方法来访问文件的特性。在本章中,我们将通过示例来探索它们。
示例 - 获取文件名称
File.name 返回文件/目录的名称,不包含父路径。
Example.groovy
def file = new File('data.txt')
println "File name: ${file.name}"
输出
运行上述程序时,我们将得到以下结果。
File name: data.txt
示例 - 获取文件的完整路径
File.path 返回文件/目录的完整路径。
Example.groovy
def file = new File('data.txt')
println "File path: ${file.path}"
输出
运行上述程序时,我们将得到以下结果。
File path: data.txt
示例 - 获取文件的绝对路径
File.absolutePath 返回文件/目录的绝对路径。
Example.groovy
def file = new File('data.txt')
println "File path: ${file.absolutePath}"
输出
运行上述程序时,我们将得到以下结果。
File path: E:\Dev\groovy\data.txt
示例 - 获取文件父目录的路径
File.parent 返回文件或目录的父路径。如果是根目录,则返回 null。
Example.groovy
def file = new File('data.txt')
println "Parent path: ${file.parent}"
输出
运行上述程序时,我们将得到以下结果。
Parent path: null
示例 - 获取文件父目录的路径
File.parent 返回文件或目录的父路径。如果是根目录,则返回 null。
Example.groovy
def file = new File('data.txt')
println "Parent path: ${file.parent}"
输出
运行上述程序时,我们将得到以下结果。
Parent path: null
示例 - 以 File 对象形式获取文件的父目录
File.parentFile 以 File 对象形式返回文件或目录的父目录。如果是根目录,则返回 null。
Example.groovy
def file = new File('data.txt')
println "Parent: ${file.parentFile}"
输出
运行上述程序时,我们将得到以下结果。
Parent: null