天天看点

《Groovy官方文档》Groovy开发套件-使用IOGroovy开发套件 第一部分

原文链接   译文链接   译者:jackwang

groovy提供了丰富的方法来操作io流。当然你也可以使用标准的java代码来进行这些操作。但是groovy提供了更多方便的方式来操作文件,流…

你可以先看看下面列举的一些方法:

the io.file class : http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/file.html

the io.inputstream class: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/inputstream.html

the io.outputstream class: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/outputstream.html

the io.reader class: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/reader.html

the io.writer class: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/io/writer.html

the nio.file.path class: http://docs.groovy-lang.org/latest/html/groovy-jdk/java/nio/file/path.html

下面的一些小节将提供一些示例来演示如何使用这些类,如果你想查看所有方法的详细用法,请阅读gdk的接口文档。

作为开篇的第一个示例,我们来看看如何使用groovy来读文件并且打印读到的所有行:

<code>new file(basedir, 'haiku.txt').eachline { line -&gt; println line }</code>

groovy的eachline方法是file类自动加载并且可有有许多的变体,比如如果你想知道行号,你可以使用以下的变体:

<code>new file(basedir, 'haiku.txt').eachline { line, nb -&gt; println "line $nb: $line" }</code>

在eachline方法体里,抛出任何异常后该方法都可以确保正常将文件流关闭。groovy的其他操作文件流的方法也提供了该特性。

比如说,有些场景你可能更喜欢用reader,该类的文件操作方法依然可以自动管理文件流。在下面的这个例子里,即便操作文件过程中抛出了异常,文件流依然可以正常关闭:

<code>def count = 0, maxsize = 3 new file(basedir,"haiku.txt").withreader { reader -&gt; while (reader.readline()) { if (++count &gt; maxsize) { throw new runtimeexception('haiku should only have 3 verses') } } }</code>

如果你想将一个文本文件中的所有行放到一个list里,你可以这样写:

<code>def list = new file(basedir, 'haiku.txt').collect {it}</code>

你甚至还可以使用as方法将一个文件内容放到一个数组中:

<code>def array = new file(basedir, 'haiku.txt') as string[]</code>

很多时候你想将一个文件的内容放到一个byte数组,你觉得需要多少代码来实现呢?groovy将这个操作变成了一行代码:

<code>byte[] contents = file.bytes</code>

使用io并不仅仅是操作文件,事实上,更多的时候你需要操作输入/输出流,这就是为什么groovy提供了非常丰富的方法来实现这一需求,你可以参见这个文档:inputstream

举个例子,你可以非常容易地从一个文件中获取一个输入流:

<code>def is = new file(basedir,'haiku.txt').newinputstream() // do something ... is.close()</code>

但是这个方式需要你手动关闭输入流,事实上groovy还提供了一种更加通用和快捷的方式,那就是使用withinputstream来操作:

<code>new file(basedir,'haiku.txt').withinputstream { stream -&gt; // do something ... }</code>

有时候你并不是想读文件而是写文件。这时一种方式是使用writer:

<code>new file(basedir,'haiku.txt').withwriter('utf-8') { writer -&gt; writer.writeline 'into the ancient pond' writer.writeline 'a frog jumps' writer.writeline 'water’s sound!' }</code>

事实上对于上面这个简单的例子,使用 &lt;&lt;操作符就绰绰有余了:

<code>new file(basedir,'haiku.txt') &lt;&lt; '''into the ancient pond a frog jumps water’s sound!'''</code>

当然,我们并不是仅仅处理文本内容,但你也可以使用writer或直接写字节:

<code>file.bytes = [66,22,11]</code>

当然你也可以直接处理输出流,比如说下面的例子演示了如何创建一个输出流并写入到一个文件:

<code>def os = new file(basedir,'data.bin').newoutputstream() // do something ... os.close()</code>

但是这个例子要求你手动关闭输出流。一种更好的做法是使用withoutputstream,任何时候只要抛出了异常它都会关闭流:

<code>new file(basedir,'data.bin').withoutputstream { stream -&gt; // do something ... }</code>

在脚本上下文里,一种很常见的场景是遍历文件树来找到特定的文件进行特定的处理。groovy提供了多种方法来做这个事情。比如说可以操作某个目录下的全部文件:

<code>dir.eachfile { file -&gt; println file.name }                         //(1) dir.eachfilematch(~/.*\.txt/) { file -&gt; println file.name }                         //(2)</code>

列举给定目录下的每个文件

在给定目录下查找匹配格式的文件

你经常需要处理更深层次的目录,可以使用 eachfilerecurse:

<code>dir.eachfilerecurse { file -&gt; println file.name }                               //(1)</code>

dir.eachfilerecurse(filetype.files) { file -&gt;

println file.name

}                               //(2)

递归列举所有文件和目录

仅仅递归列举文件

需要更加复杂的遍历技术,可以使用 traverse方法,需要你设置一个特定的递归标识来终止递归:

<code>dir.traverse { file -&gt; if (file.directory &amp;&amp; file.name=='bin') { filevisitresult.terminate                   //(1) } else { println file.name filevisitresult.continue                   //(2) } }</code>

如果当前文件是一个目录并且名字是bin,停止遍历

打印文件名并继续

在java里,使用java.io.dataoutputstream 和 java.io.datainputstream类来序列化和反序列化数据是非常常见的。groovy里,这步操作将变得更加容易,比如,你可以序列化数据到一个文件然后使用下面的代码反序列:

<code>boolean b = true string message = 'hello from groovy' // serialize data into a file file.withdataoutputstream { out -&gt; out.writeboolean(b) out.writeutf(message) } // ... // then read it back file.withdatainputstream { input -&gt; assert input.readboolean() == b assert input.readutf() == message }</code>

类似地,如果你想要序列化的数据实现了serializable接口,你可以使用一个对象输出流来处理,如下面的示例所示:

<code>person p = new person(name:'bob', age:76) // serialize data into a file file.withobjectoutputstream { out -&gt; out.writeobject(p) } // ... // then read it back file.withobjectinputstream { input -&gt; def p2 = input.readobject() assert p2.name == p.name assert p2.age == p.age }</code>

前面的章节描述了使用groovy来处理文件,readers或流是一件很简单的是。但是在一些领域向系统管理员或开发经常需要和外部进程进行交互。

groovy提供了一种简单的方式来执行命令行进程。仅仅需要将命令行写成字符串然后调用execute方法。举个例子,子啊一个*nix机器上(或者一台安装了*nix命令执行环境的windows机器上)你可以执行下面的代码:

<code>def process = "ls -l".execute()             (1) println "found text ${process.text}"       (2)</code>

在外部进程执行ls命令

处理输出并且返回文本

execute方法返回一个java.lang.process实例,可以使用in/out/err流来处理,通过返回值可以查看处理情况。

eg:这里有一个和上面命令类似但是现在是每次处理一个结果流:

<code>def process = "ls -l".execute()             (1) process.in.eachline { line -&gt;               (2) println line                           (3) }</code>

对每个输入流进行处理

打印line的内容

in 相当于标准输出命令中的输入流, out指代你发送到进程(标准输入流)中的数据的流。

记住,对于内置的shell命令需要有特殊的处理,因此如果你想在一台windows机器上列一个某个目录的所有文件可以这样写:

<code>def process = "dir".execute() println "${process.text}"</code>

当出现 cannot run program “dir”: createprocess error=2, the system cannot find the file specified. 时你将收到一个ioexception

这是因为dir命令是windows shell(cmd.exe)内置的命令。不能仅仅是执行dir,你应该这样写:

<code>def process = "cmd /c dir".execute() println "${process.text}"</code>

同样,因为这个功能使用了java.lang.process 类,这个类的一些缺陷就必须考虑进去,javadoc关于这个类是这样说的:

因为一些原生平台仅仅提供受限缓冲区大小的标准输入输出流,因此对于失败的写输入流操作或读输出流操作可能会造成进程阻塞甚至死锁。

因为这一点,groovy 提供了一个额外的帮助方法类使得流处理起来更加方便。

下面的例子是如何无阻塞处理素有的输出(包括错误流输出):

<code>def p = "rm -f foo.tmp".execute([], tmpdir) p.consumeprocessoutput() p.waitfor()</code>

consumeprocessoutput 也有一些变体来使用stringbuffer,inputstream,outputstream等等,完整的例子可以参考gdk api for java.lang.process

除此之外,也有一个pipeto命令(对应 | (管道))使得输出流可以承接到另外一个进程的输入流。

这有一些示例的使用:

<code>proc1 = 'ls'.execute() proc2 = 'tr -d o'.execute() proc3 = 'tr -d e'.execute() proc4 = 'tr -d i'.execute() proc1 | proc2 | proc3 | proc4 proc4.waitfor() if (proc4.exitvalue()) { println proc4.err.text } else { println proc4.text }</code>

处理错误:

<code>def sout = new stringbuilder() def serr = new stringbuilder() proc2 = 'tr -d o'.execute() proc3 = 'tr -d e'.execute() proc4 = 'tr -d i'.execute() proc4.consumeprocessoutput(sout, serr) proc2 | proc3 | proc4 [proc2, proc3].each { it.consumeprocesserrorstream(serr) } proc2.withwriter { writer -&gt; writer &lt;&lt; 'testfile.groovy' } proc4.waitfororkill(1000) println "standard output: $sout" println "standard error: $serr"</code>