-
-
Save alanland/5847446 to your computer and use it in GitHub Desktop.
Groovy 文件操作
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 创建文件夹 | |
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