使用Groovy操作文件

1. 读文件

读文件内容

在groovy中输出文件的内容:

println new File("tmp.csv").text

上面代码非常简单,没有流的出现,没有资源关闭的出现,也没有异常控制的出现,所有的这些groovy已经搞定了。

读取每一行内容:

File file = new File('tmp.csv')
assert file.name == 'tmp.csv'
assert ! file.isAbsolute()
assert file.path == 'tmp.csv'
assert file.parent == null

//使用系统默认的编码处理文件流  
file.eachLine {println it }  
//指定处理流的编码
file.eachLine("UTF-8") { println it }

file.eachLine("UTF-8",10) {str,no->  
    println str  
    println no }
对文件中每一行的内容做处理:

file.splitEachLine("\t") { println it  }

//以大写行式输出文件内容  
lineList = file.readLines();  
liineList.each {  
  println it.toUpperCase();  
}

file.filterLine {String str->  
    if (str.contains('code'))  
        println str  
}.writeTo(new PrintWriter(System.out)) 

解析 xml 文件

<?xml version="1.0" encoding="UTF-8"?> 
<customers> 
  <corporate> 
    <customer name="bill gates" company="microsoft"></customer> 
    <customer name="steve jobs" company="apple"></customer> 
    <customer name="bill dyh" company="sun"></customer> 
  </corporate> 
  <consumer> 
    <customer name="jone Doe"></customer> 
    <customer name="jane Doe"></customer>    
  </consumer> 
</customers>

def customers = new XmlSlurper().parse(new File("customers.xml")) 
/*对文件进行解析*/ 
for(customer in customers.corporate.customer){ 
    println "${customer.@name} works for${customer.@company}"; 
} 

解析 propeties 文件

参考 groovy: How to access to properties file?,代码如下:

def props = new Properties()
new File("message.properties").withInputStream { 
  stream -> props.load(stream) 
}
// accessing the property from Properties object using Groovy's map notation
println "capacity.created=" + props["capacity.created"]

def config = new ConfigSlurper().parse(props)
// accessing the property from ConfigSlurper object using GPath expression
println "capacity.created=" + config.capacity.created

另外一种方式:

def config = new ConfigSlurper().parse(new File("message.groovy").text)
message.groovy 内容如下:

capacity {
  created="x"
  modified="y"
}

2. 操作目录

列出目录所有文件(包含子文件夹,子文件夹内文件) :

def dir = new File(dirName)  
if (dir.isDirectory()) {  
    dir.eachFileRecurse { file ->  
        println file  
    }  
} 

dir.eachFileMatch(~/.*\.txt/) {File it-> println it.name  } //使正则表达式匹配文件名  
dir.eachFileMatch(FILES, ~/.*\.txt/) { File it-> println it.name  } 

3. 写文件

import java.io.File  
  
def writeFile(fileName) {  
    def file = new File(fileName)  
      
    if (file.exists())   
        file.delete()  
          
    def printWriter = file.newPrintWriter() //   
      
    printWriter.write('The first content of file')  
    printWriter.write('\n')  
    printWriter.write('The first content of file')  
      
    printWriter.flush()  
    printWriter.close()  

除了  file.newPrintWriter()  可以得到一个 PrintWriter,类似方法还有  file.newInputStream()   file.newObjectInputStream() 等。

更简洁写法:

new File(fileName).withPrintWriter { printWriter ->  
     printWriter.println('The first content of file')  
}  


  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值