概述
一、读取文件
class FirstTest{
static void main(String[] args) {
new File("test.txt").eachLine{
line -> println "line: $line"
}
}
}
二、读取文件的内容到字符串
class FirstTest{
static void main(String[] args) {
File file = new File("test.txt")
println file.text
}
}
三、写入文件
class FirstTest{
static void main(String[] args) {
new File('./',"test.txt").withWriter('utf-8'){
writer -> writer.writeLine('Hello World')
}
}
}
四、获取文件大小
class FirstTest{
static void main(String[] args) {
File file = new File('test.txt')
println file.length()
}
}
五、获取文件绝对路径
class FirstTest{
static void main(String[] args) {
File file = new File('test.txt')
println file.absolutePath
}
}
六、测试文件是否为文件、目录
class FirstTest{
static void main(String[] args) {
def file = new File('D:/')
println file.isFile()
println file.isDirectory()
}
}
七、创建目录
class FirstTest{
static void main(String[] args) {
def file = new File("D:/test")
file.mkdir()
}
}
八、删除文件
class FirstTest{
static void main(String[] args) {
def file = new File('test.txt')
file.delete()
}
}
九、复制文件
class FirstTest{
static void main(String[] args) {
def src = new File('D:/test/1.txt')
def dst = new File('D:/test/2.txt')
dst << src.text
}
}
十、获取目录内容
- 显示机器上的驱动器
class FirstTest{
static void main(String[] args) {
def rootFiles = new File("./").listRoots()
rootFiles.each{
file -> println file.absolutePath
}
}
}
- 显示指定目录中的文件
class FirstTest{
static void main(String[] args) {
new File("D:\StaticFile").eachFile(){
file -> println file.getAbsolutePath()
}
}
}
- 递归显示指定目录下所有目录和文件
class FirstTest{
static void main(String[] args) {
new File("D:\StaticFile").eachFileRecurse(){
file -> println file.getAbsolutePath()
}
}
}
最后
以上就是寂寞白云为你收集整理的Groovy~Groovy的IO操作的全部内容,希望文章能够帮你解决Groovy~Groovy的IO操作所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复