Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@alanland
Last active August 6, 2023 04:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alanland/5847446 to your computer and use it in GitHub Desktop.
Save alanland/5847446 to your computer and use it in GitHub Desktop.
Groovy 文件操作
// 创建文件夹
wasCreated = new File('mydir').mkdir()
wasCreated = new File('mydir/subdir').mkdirs()
// 写文件
f = new File('myfile.txt')
f.write('hello world!')
// 写文件2
f = new File(‘myfile.txt’)
f.text = ‘Hello World!’
// 追加文件
f = new File('myfile.txt')
f.append('hello again!')
// 遍历文件
def dir = new File('/home/groovy/projects/test/src')
dir.traverse(
type:FileType.FILES,
nameFilter:~/.*\.groovy/
) {
println it
};
// 遍历文件 with depth. 0 -> max depth
def dir = new File('/home/groovy/projects/test/src')
dir.traverse(
type:FileType.FILES,
nameFilter:~/.*\.groovy/,
maxDepth:0
) {
println it
};
// 不同文件类型
dir.traverse(
type:FileType.FILES,
nameFilter:~/.*\.jar|.*\.java|.*\.xml/
) {
println it
};
// 列出文件
def dir = new File('/home')
dir.eachFile {
if (it.isFile()) {
println it.canonicalPath
}
}
//
def dir = new File('/home')
dir.traverse {
println it
}
//
def dir = new File('/home')
dir.traverse(maxDepth:0) {
println it
};
// 找出文件路径
file = new File('yourfile.txt')
println file.canonicalPath
// 保存一个网页到文件
def address = 'http://groovy.codehaus.org/'
def filename = 'groovy.html'
def file = new FileOutputStream(filename)
def out = new BufferedOutputStream(file)
out << new URL(address).openStream()
out.close()
// read file line by line
def file = new File('hello.txt')
file.eachLine { line ->
println line
}
// read file
def input = new File('hello.txt')
println input.text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment