1. eachLine -- 打开和读取文件的每一行

new File("foo.txt").eachLine {
println it.toUpperCase();
}

2. readLines -- 其作用基本与 eachLine 相同,但它不接受闭包为参数,而是把文件行读到一个 List 中

lineList = new File("foo.txt").readLines();
lineList.each {
println it.toUpperCase();
}

3. splitEachLine -- 读取文件的每一行,然后对行以指定分隔符分割成数组。不用再多说了,这个方法对处理 CSV 文件那可是相当的高效。

lineList = new File("foo.csv").splitEachLine(",") {
println "name=${it[0]} balance=${it[1]}";
}

4. eachByte -- 处理二进制文件,以字节级访问文件,这个方法相当于 eachLine() 方法。

new File("foo.bin").eachByte { print it; }

5. readBytes -- 自然,处理二进制文件,以字节级访问文件,这个方法相当于 readLines() 方法了

byteList = new File("foo.bin").readBytes();
byteList.each {
println it;
}

6. write -- Groovy 用这个方法写文件真是太直观了

new File("foo.txt").write("testing testing");

new File("foo.txt").write("""
This is
just a test file
to play with
""");

以上使用了三重引用语法,其中的文本保留格式的写入到文件中。注意上面写法在文件首尾都会有一个空行,除非起始和结束字符都要紧贴 """;还有上面方法写的文件用词本打开会是挤在一行,用 editplus 打开是多行,因为它采用的是 linux 下的 /n 换行,而不是 windows 下的 /r/n 换行。、

7. append -- 与 write 覆写文件不同,append 是在文件后追加内容

new File("foo.txt").append("""/
This is
just a test file
to play withff
"""
);

8. eachFile -- 功能上类似 java.io.File 的 listFiles() 方法。用来列举路径中的每个文件(包括目录),传给闭包处理

new File(".").eachFile {   //这里的 File 表示的是一个路径
println it.getName(); //eachFile() 列出的每一项是一个 File 实例
}

9. eachFileRecurse -- 以深度优先的方式递归遍历路径,列出文件(包括目录),传给闭包处理

new File(".").eachFileRecurse {   //这里的 File 表示的是一个路径
println it.getPath(); //eachFile() 列出的每一项是一个 File 实例
}

10. …… 再重复一下,其他 Groovy 对 java.io.File 的扩展方法请参考 http://groovy.codehaus.org/groovy-jdk/java/io/File.html

eachDir()、eachDirMatch()、eachDirRecurse()、eachFileMatch()、filterLine()、
newInputStream()、newOutputStream()、newReader()、newPrintWriter()、
withInputStream()、withOutputStream()、withReader()、withPrintWriter()
等等。还要留意一下有一些方法是可以指定字符集的。

----

操作目录

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

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 }
 

写文件

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')
}

解析 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").toURL())

message.groovy 内容如下:

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

Groovy读取文件信息的更多相关文章

  1. linux 读取文件信息并且输出

    版权为个人所有,欢迎转载如转载请说明出处.(东北大亨) http://www.cnblogs.com/northeastTycoon/p/5513231.html 以下为读取文件信息做输出操作. 1. ...

  2. HTML5的File API读取文件信息

    html结构: <div id="fileImage"></div> <input type="file" value=" ...

  3. .net上传文件,利用npoi读取文件信息到datatable里

    整理代码,.net上传文件,利用npoi读取文件到datatable里,使用了FileUpload控件,代码如下: protected void Button1_Click(object sender ...

  4. pytest 9 pytest-datadir读取文件信息

    安装:pip install pytest-datadir 介绍:用于操作测试数据目录和文件的插件.pytest-datadir他会寻找包含测试模块名字的文件夹或者全局的一个文件夹名字为data下的数 ...

  5. 读取文件信息,并通过sscanf从中获取所需数据

    #include <stdio.h> #include <stdlib.h> #include <string.h> int file_length(char* f ...

  6. python读取文件内的IP信息 练习

    代码如下: #导包 import fileinput import re def readArw(): for line in fileinput.input(r"G:/raw.txt&qu ...

  7. Servlet读取文件的最好的方式

    在java web 开发的时候不可避免的会读取文本信息,但是方式不同,所付出的代价也是不一样的,今天学到了一个比较好的实用性的技巧,拿来与大家分享一下. 读取属性配置文件 之所以说成是读取属性(pro ...

  8. 使用QFileInfo类获取文件信息(在NTFS文件系统上,出于性能考虑,文件的所有权和权限检查在默认情况下是被禁用的,通过qt_ntfs_permission_lookup开启和操作。absolutePath()必须查询文件系统。而path()函数,可以直接作用于文件名本身,所以,path() 函数的运行会更快)

    版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/Amnes1a/article/details/65444966QFileInfo类为我们提供了系统无 ...

  9. QT_8_Qt中的事件处理_定时器事件_定时器类_事件分发器_事件过滤器_绘图事件_高级绘图事件_绘图设备_QFile 文件读写_QFileInfo文件信息

    Qt中的事件处理 1.1. 捕获QLabel中是鼠标事件 1.2. enterevent 鼠标进入 1.3. leaveevent 鼠标离开 1.4. 鼠标按下MyLabel::mousePressE ...

随机推荐

  1. informatica 学习总结

    问:什么是BI? 答:BI是商务智能,它包含的应用系统和技术较宽泛,通过收集,存储,分析和提供对数据的访问,来帮助企业用户做出更好的商务决策. BI应用包括决策支持,查询和报表,联机分析处理OLAP, ...

  2. (转)java提高篇(二)-----理解java的三大特性之继承

    在<Think in java>中有这样一句话:复用代码是Java众多引人注目的功能之一.但要想成为极具革命性的语言,仅仅能够复制代码并对加以改变是不够的,它还必须能够做更多的事情.在这句 ...

  3. 用letsencrypt搭建免费的https网站

    环境:阿里云服务器centos7.3,nignx,letsencrypt做免费的https证书 Let’s Encrypt官网:https://letsencrypt.org/ 1.服务器开放端口:4 ...

  4. Codeforces Round #427 (Div. 2)

    B. The number on the board 题意: 有一个数字,它的每个数位上的数字的和不小于等于k.现在他改变了若干位,变成了一个新的数n,问现在的数和原来的数最多有多少位不同. 思路: ...

  5. JavaScript中的call()、apply()与bind():

    关于call()与apply(): 在JavaScript中,每个函数都有call与apply(),这两个函数都是用来改变函数体内this的指向,并调用相关的参数. 看一个例子: 定义一个animal ...

  6. 走过夏天,我的H5旅程,一路慢行

    <!DOCTYPE html> <!-- 文档类型声明:让浏览器,按照html5的标准对代码进行解释和执行. 文档类型声明必不可少,而且,必须放在文档最上方. 如果不写文档类型声明, ...

  7. git入门(3)git checkout 和git branch分支的创建和删除

    在一个项目中,需要多人同时开发,协同coding 要求: 开发时请用开发分支daily/0.0.1, 禁止直接使用master分支开发新建分支 git checkout -b daily/0.0.1 ...

  8. Python 爬虫抓取代理IP,并检测联通性

    帮朋友抓了一些代理IP,并根据测试联的通性,放在了不通的文件夹下.特将源码分享 注意: 1,环境Python3.5 2,安装BeautifulSoup4  requests 代码如下: 1 2 3 4 ...

  9. 模拟生产搭建Standby RAC实验环境(11.2.0.4 DG)

    模拟生产搭建Standby RAC实验环境(11.2.0.4 DG) 环境:RHEL 6.5 + Oracle 11.2.0.4 GI.DB 1.需求背景介绍 2.准备工作 3.主库配置 4.备库配置 ...

  10. 只需要一点点C++基础,新手也可以制作单机游戏内存修改器

    声明:本文只是为了初学C++的,能够做出一些实用的东西,跳出管理系统的束缚,提升学习的兴趣,在这里选取了单机游戏,请不要尝试在线游戏,违发而已未必可行.序:首先我们需要一个Qt+VS环境Qt从http ...