Groovy的文件操作

groovy 文件操作,对java原有的io进行了扩展,增加了许多闭包后省去了很多逻辑无关代码,同时自动进行资源管理和异常处理。 

读取文件内容: 
使用java代码的基本写法

FileInputStream fin = null;  
try {  
    fin = new FileInputStream("test.txt");  
    BufferedReader br = new BufferedReader(new InputStreamReader(fin));  
    String line = null;  
    while ((line = br.readLine()) != null) {  
        System.out.println(line);  
    }  
}  catch (FileNotFoundException e) {  
    // TODO: handle exception  
}  catch (IOException e) {  
    // TODO: handle exception  
}  finally {  
    try {  
        if (fin != null) {  
            fin.close();  
        }  
    }  
    catch (IOException e2) {  
        // TODO: handle exception  
    }  
}  
对一个文件进行读取的时候,基本上都会用到上面的代码,重复的写这些代码让人感觉很枯燥,同时在阅读 
这样的代码的时候也极易干扰视线。真正要干的事情也就是把文件内容输出而已。 
而在groovy中输出文件的内容仅需要一行代码 
println new File("test.txt").text 

代码里没有流的出现,没有资源关闭的出现,也没有异常控制的出现,所有的这些groovy已经搞定了。 
看到这样的代码是否有种清风拂面的感觉呢?呵呵! 

下面介绍下groovy中File的一些接口: 
1、对文件内容的操作 

File file = new File('C:\\Users\\berdy\\Desktop\\test.txt')  
//使用系统默认的编码处理文件流  
file.eachLine {println it }  
//指定处理流的编码  
file.eachLine("utf8") {println it  }  
//指定文件内容行标的起始数字,默认为1,根据需要设置为其他数值  
file.eachLine("utf8",10) {str,lineNumber->  
    println str  
    println lineNumber }  
  
//对文件内容的每一行进行分割处理,比较常用在处理csv文件  
file.splitEachLine(",") {println it  }  
  
//在闭包中定义过滤逻辑,对文件内容进行过滤处理  
file.filterLine {String str->  
    if (str.contains('code'))  
        println str  
}.writeTo(new PrintWriter(System.out))  
  
file.append('hello world!')  
  
//转为Writable对象,可重定向输出  
file.asWritable()  

2、对目录进行操作 

File file = new File('.')  
file.eachFileMatch(~/.*\.txt/) {File it-> println it.name  } //使正则表达式匹配文件名  
file.eachFileMatch(FILES, ~/.*\.txt/) { File it-> println it.name  }  
  
new File(".").eachFileRecurse {  
    println it.getPath();  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值