Groovy读取文件信息

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 "${[email protected]} works for${[email protected]}";
} 

解析 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"
}
时间: 2024-08-29 00:31:04

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

读取文件信息

1 /** 2 * 读取文件信息 3 * @param src 文件路径 4 * @return String 5 */ 6 public static String readCacert(String src) { 7 StringBuilder sb = new StringBuilder(); 8 try { 9 BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File

HTML5的File API读取文件信息

html结构: <div id="fileImage"></div> <input type="file" value="upload" id="fileInput"> <p id="fileInfo"></p> css样式: #fileImage{width: 300px;height: 300px; margin: 20px auto;back

Android中的meminfo,cpuinfo(二):用代码来读取文件信息

1. 简介: 上篇,介绍了meminfo和cpuinfo文件,本篇给出程序例程,用代码的方式来获取它们的值. 以memino为例. 2. 代码: public static List<Long> getMeminfo() { List<Long> memInfoList = new ArrayList<Long>(); try { BufferedReader reader = new BufferedReader(new InputStreamReader(new F

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

#include <stdio.h> #include <stdlib.h> #include <string.h> int file_length(char* fileName) { FILE* fp; int file_set_val,file_end_val; fp = fopen(fileName, "r"); if(fp == NULL) { printf("[%s][%s]read file fail\r\n",__L

phantomjs读取文件转换数组

//要读取的文件路径,支持TXT和CSV var openFilepath="lieBiao.txt"; phantom.outputEncoding="GB2312";//输出编码 var idList=new Array(); //读取文件信息的方法 function ReadIdList(){ console.log('reading...'); //加载读取文件模块 var fs = require("fs"); fs.encoding=

PHP文件操作 之读取目录信息

//定义一个函数 读取目录信息的函数 function dirInfo($dirName) { //判断目录是否存在 if (!file_exists($dirName)) { die('目录不存在!'); } //判断是否是目录 if (!is_dir($dirName)) { die('您所遍历的不是目录!'); } //打开目录 $d = opendir($dirName); //判断打开目录是否成功 if (!$d) { die('打开目录失败!'); } //读取目录 while ($

asp.net简单读取xml文件信息

xml文件格式如下:     <?xml   version="1.0"   encoding="utf-8"?>         <userdata   createuser="false">         <dataconnection>             <server>localhost</server>             <uid>sa</uid

vbs读取文件内的信息将非有效数据移动到指定路径

vbs读取文件内的信息将非有效数据移动到指定路径 之前我们介绍了,通过读取文件内的信息将相同的数据拷贝到指定目录,执行后我们可以利用有效的信息,但是时间长的话服务器上的可用空间也会越来越多,所以再次就想通过vbs脚本来判断数据是否有用,来提高服务器的可用空间. 思路是这样的,通过从domino目录下导出有效的数据,然后通过本地的数据盘进行比对,将无效的数据库移动到其他盘操作,如果在不影响数据完整性的情况下在做删除,那如何操作呢,首先是定义一个xlsx文件(1.xlss),文件可以任意命名,但是需

C++开发人脸性别识别教程(8)——搭建MFC框架之读取文件夹信息

在上一篇博客中我们已经绘制了MFC界面,在这篇博客中我们将添加响应代码,为MFC框架添加一个最基本的功能:打开一个文件夹. 一.添加相关头文件 这里头文件主要包含三类:opencv头文件.批量读取文件相关的头文件.CvvImage.这里需要强调CvvImage这个头文件,这个是用来关联OpenCv和picture控件,并且这个头文件是隶属于OpenCv1.x的,在2.x版本中已经将这个类移除,因此需要手动下载这两个文件(CvvImage.h和CvvImage.cpp),下载地址:CvvImage