Groovy 之文件操作
|
? 一:Java 与 Groovy 读文件操作比较
从上面可看到,采用 Java 传统方式来读取文件内容,不仅代码行多,而且还必须自己用 try/catch/finally 来处理异常和资源的关闭。现在马上来看看 Groovy 完成以上工作的代码是怎么的,只要一行代码: ? 1.
text = new File("foo.txt").getText();
? 不需要 Reader 或 Inputstream、不用关闭语名和异常处理。我们所要做的就是编写业务逻辑,剩下的工作 Groovy 会帮你料理的。当然,如果文件找不到,也是会出现 java.io.FileNotFoundException 异常的。你可以捕获这个要处理的异常,但仍然不必担心资源的释放。 ? 1.
try{
2.
????text = new File("foo.txt").getText();
3.
} catch(Exception e){
4.
}
? 1. eachLine -- 打开和读取文件的每一行 1.
new File("foo.txt").eachLine {?
2.
????println it.toUpperCase();
3.
}
1.
lineList = new File("foo.txt").readLines();
2.
lineList.each {?
3.
????println it.toUpperCase();
4.
}
1.
lineList = new File("foo.csv").splitEachLine(",") {
2.
????println "name=${it[0]} balance=${it[1]}";
3.
}
1.
new File("foo.bin").eachByte { print it; }
1.
byteList = new File("foo.bin").readBytes();
2.
byteList.each {?
3.
????println it;
4.
}
1.
new File("foo.txt").write("testing testing");
2.
??
3.
new File("foo.txt").write("""
4.
This is
5.
just a test file
6.
to play with
7.
""");
1.
new File("foo.txt").append("""/
2.
This is??
3.
just a test file??
4.
to play withff
5.
"""??
6.
);
8. eachFile -- 功能上类似 java.io.File 的 listFiles() 方法。用来列举路径中的每个文件(包括目录),传给闭包处理 1.
new File(".").eachFile {?? //这里的 File 表示的是一个路径
2.
????println it.getName();? //eachFile() 列出的每一项是一个 File 实例
3.
}
1.
new File(".").eachFileRecurse {?? //这里的 File 表示的是一个路径
2.
????println it.getPath();? //eachFile() 列出的每一项是一个 File 实例
3.
}
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
