Groovy基本使用(5):文件I/O 处理

来源:互联网 发布:linux rpm包安装位置 编辑:程序博客网 时间:2024/05/17 02:20

Groovy 文件I/O 处理

Groovy 中处理文件 I/O 时,除了可以使用 Java 本身的IO类,如:    java.io.File, java.io.InputStream,java.io.OutputStream,java.io.Reader,java.io.Writer 之外,本身也提供了一些简单的类来完成文件 I/O 的一些基本操作;

读取文件

写入文件

1
def strOut = """Hello world!
2
Welcome to Groovy!
3
This is some output to the new file.""";
4
5
File fileOut = new File("./out.txt");
6
fileOut.withWriter('utf-8'){
7
    writer -> writer.writeLine(strOut);
8
}

获取文件信息

目录操作
1
//创建目录
2
File dir = new File("./testDir");
3
dir.mkdir();
4
5
//列举机器上的驱动器
6
def rootFiles = new File("test").listRoots() 
7
rootFiles.each { 
8
    file -> println file.absolutePath 
9
}
10
//output: C:\ 
11
//        D:\
12
13
14
//列举指定目录下的所有文件
15
def file = new File("E:/test");
16
file.eachFIleResource(){
17
    file -> println(file.getAbsolutePath());
18
}
19
    
20
21

删除文件

复制文件

1
File src = new File("./test.txt");
2
File dest = new File("./dest.txt");
3
dst << src;


更多关于 Groovy 类库的使用,参见官方 API 文档;







原创粉丝点击