「Groovy」- 操作文件(读取、写入) @20210223
检查文件是否存在、可读等等
File file = new File("out.txt")
println file.exists()
println file.canRead()
向文件写入文本
File file = new File("out.txt")
file.write "First line\n"
file << "Second line\n"
file.append("hello\n")
println file.text
获取文件全部内容
File file = new File('examples/data/count_digits.txt')
// 获取文件全部内容
println file.getText('UTF-8')
println file.text
// 获得文件的输入流
def inputStream = file.newInputStream()
遍历文件的全部行
File file = new File("/path/to/file")
// 第一种方法
def lines = file.readLines()
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)
相关文章
「Apache Groovy」- 运行 Shell 命令
「Groovy」- 处理 Object 与 JSON String 之间的转换
「Apache Groovy」- 连接 SQLite 数据库
「Groovy」- 操作 HTML 文档
「Groovy」- 彩色化输出日志
参考文献
Groovy: reading and writing files - appending content
Working with IO
How to read a file in Groovy into a string? - Stack Overflow
json - Groovy file check - Stack Overflow
Set last modified timestamp of a file using jimfs in Java - Stack Overflow
浙公网安备 33010602011771号