Groovy对文件的操作
对文件的遍历 假设文件的原始内容为:
1hello,world 2这里是北京 3andorid and ios are good system
第一种方法:使用 eachLine()
1//1.1 new 一个File 2def file = new File(filepath) 3 4//1.2 groovy对文件的遍历 5file.eachLine { 6 //打印每一行内容 7 line -> println line 8} 9 10//输出 11hello,world 12这里是北京 13andorid and ios are good system
第二种方法:使用File的getText()
1def content = file.getText() 2println content 3//输出 4hello,world 5这里是北京 6andorid and ios are good system
是不是更简单,直接调用一个方法就OK了,比Java操作文件要简单太多了吧
第三种方法:使用 file.readLines()方法
1def list = file.readLines() 2list.collect { 3 println it 4} 5 6println "文件有" + list.size() + "行" 7//输出 8hello,world 9这里是北京 10andorid and ios are good system 11文件有3行
是不是很方便,readLines()函数直接把文件内容以行为单位读取到一个List中,这样操作就更方便了
第四种方法:读取文件部分内容
1//读取前20个字符 2def reader = file.withReader { 3 reader -> 4 char[] buffer = new char[20] 5 reader.read(buffer) 6 return buffer 7} 8 9println reader 10//输出 11hello,world 12这里是北京 13an
如何拷贝文件?
我们写一个方法,把刚才的文件拷贝到另一个文件中去,代码如下:
1def copy(String sourcePath, String destPath) { 2 try { 3 //1 创建目标文件 4 def destFile = new File(destPath) 5 if (!destFile.exists()) { 6 destFile.createNewFile() 7 } 8 9 //2 开始拷贝 10 new File(sourcePath).withReader { reader -> 11 def lines = reader.readLines() 12 destFile.withWriter { writer -> 13 lines.each { 14 //把每一行都写入到目标文件中 15 line -> writer.append(line+"\r\n") 16 } 17 } 18 } 19 20 return true 21 } catch (Exception e) { 22 return false 23 } 24}
读写对象 有时候我们会有这样的需求,需要把我们的bean对象写入到文件中,用到的时候再读出来,下面我们就来实现这样的功能,代码如下:
1//将一个对象写入到文件中 2def saveObject(Object object, String path) { 3 try { 4 //1 首先创建目标文件 5 def destFile = new File(path) 6 if (!destFile.exists()) { 7 destFile.createNewFile() 8 } 9 10 destFile.withObjectOutputStream { out -> 11 out.writeObject(object) 12 } 13 14 return true 15 } catch (Exception e) { 16 } 17 18 return false; 19} 20 21//从一个文件中读到bean 22def readObject(String path) { 23 def obj = null 24 try { 25 //1 先判断文件是否存在 26 def file = new File(path) 27 if (!file.exists()) { 28 return null 29 } 30 31 //2 从文件中读取对象 32 file.withObjectInputStream { reader -> 33 obj = reader.readObject(); 34 } 35 36 return obj 37 } catch (Exception e) { 38 } 39 40 return null 41} 42
Groovy对xml文件的操作
1/** 2 test.xml 文件的内容如下: 3 4 <langs type="current"> 5 <language1>Java</language1> 6 <language2>Groovy</language2> 7 <language3>JavaScript</language3> 8 </langs> 9 */ 10 11//一行代码就解析了xml 12def langs = new XmlParser().parse("test.xml") 13 14//打印出node的属性 15println langs.attribute('type') 16 17//对xml文件的遍历 18langs.each { 19 println it.text() 20} 21 22//输出 23current 24Java 25Groovy 26JavaScript
以上就是groovy对文件的操作
