前言
- 本篇学习使用groovy来读取文件内容和将内容写入文件
数据准备
- 新建一个data.txt文件,内容如下
姓名:大海
年龄:28
哪里人:辽宁人
工作地:北京
职业:测试工程师
读取文件
读取为字符串
// 文件路径
def filePath = "data.txt"
File file = new File(filePath)
// 以字符串方式全部读取
println file.text
读取到list中
def filePath = "data.txt"
File file = new File(filePath)
// 读取到list
def list = file.collect { it }
println list
读取到数组中
def filePath = "data.txt"
File file = new File(filePath)
// 读取到数组
def arr = file as String[]
println arr
按行读取
- 一行一行读取为字符串
def filePath = "data.txt"
File file = new File(filePath)
// 一行一行读取
file.eachLine {line ->
println line
}
- 每行读取到一个list中
def filePath = "data.txt"
File file = new File(filePath)
// 每行读取到一个list中
def list2 = file.readLines()
println list2
二进制方式读取
// 二进制文件读取
def filePath = "data.txt"
File file = new File(filePath)
byte[] contents = file.bytes
println contents
写入文件
- 覆盖写入,运行两次会把上次写入内容覆盖
// 写入的文件路径
def filePath1 = "data1.txt"
File file2 = new File(filePath1)
// 写入文件,两种方式
file2.write("This is line1")
file2 << "\nThis is line2"
println file2.text
- 追加写入,运行两次,会有两行内容
// 写入文件
def filePath1 = "../data1.txt"
File file2 = new File(filePath1)
// 写入文件,两种方式
println file2.text
// 追加写入文件
file2.append("\nThis is line3")
println file2.text