「Groovy」- 常用文件操作

基本操作(增删改查)

增(创建文件)

How to create text file using Groovy? – Stack Overflow

def newFile = new File("/path/to/file")
newFile.createNewFile() // 此时,将创建空文件,如果文件存在,则返回 false 值

def newFile = new File("/path/to/file")
newFile.text = "xxxxx" // 此时,将创建文件,并写入内容

删(移除文件)

Delete a file with groovy

def file = new File("/path/to/file")
file.delete() // 删除文件

改(修改文件)

File file = new File("out.txt")

file.write "First line\n"
file << "Second line\n"
file.append("hello\n")

println file.text

查 | 获取内容,检查文件是否存在、可读、……

Groovy: reading and writing files – appending content
How to read a file in Groovy into a string? – Stack Overflow

File file = new File("out.txt")

// 获取文件全部内容
println file.getText('UTF-8')
println file.text

// 判断文件的某些属性
println file.exists()
println file.canRead()
println file.isDirectory()

// 获得文件的输入流(读取)
def inputStream = file.newInputStream()

路径操作

// 获取绝对路径
file.getAbsolutePath()

// 获取父级路径
file.getParent() // => return a String
file.getParentFile() // => return a File object

以行为单位,遍历文件内容

File file = new File("/path/to/file")

// 第一种方法
def lines = file.readLines() // String[]
for (line in lines) {
    // ...
}

// 第二种方法
file.eachLine { line, nb ->
    println "Line $nb: $line"
}

时间属性(修改时间、创建时间)

File file = new File("/path/to/file");

// 获取文件修改时间
Long actualLastModified = file.lastModified();

// 设置文件修改时间
file.setLastModified(actualLastModified)

参考文献

Working with IO
json – Groovy file check – Stack Overflow
Set last modified timestamp of a file using jimfs in Java – Stack Overflow
File getAbsolutePath() method in Java with Examples – GeeksforGeeks
java – How do I get a file’s directory using the File object? – Stack Overflow
File getParentFile() method in Java with Examples – GeeksforGeeks

目录 | Folder

递归创建目录 | java – Recursively create directory – Stack Overflow

import java.nio.file.Files;
import java.nio.file.Paths;

...

Files.createDirectories(Paths.get("a/b/c"));