输入输出

对于I/O的操作,Groovy提供了很多助手方法(helper methods),而且这些方法完全可以应用在Java的Reader/Writer、InputStream/OutputStream、File 、URL类上。

使用闭包处理可以保证资源能被适当的释放,而不管是否发生了异常。比如要遍历文件的每一行,可以使用如下代码:

new File("foo.txt").eachLine { line -> println(line) }

如果不管什么原因导致了println()方法抛出了异常,eachLine() 方法可以确保文件资源被正确地释放,类似的如果在读取的时候发生了异常,资源也会被正确的释放。

如果你想使用reader/writer对象或者input/output流对象,也有相应的助手方法可以通过闭包来处理这些资源,同理如果有异常发生,资源也会被自动的释放。例如:

new File("foo.txt").withReader { reader ->
	while (true) {
		def line = reader.readLine()
	}
}

def fields = ["a":"1", "b":"2", "c":"3"]
new File("foo.ini").withWriter { out ->
        fields.each() { key, value ->
                out.writeLine("${key}=${value}")
        }
}

欲了解更多的I/O,请看Streams、Readers、Writers

使用进程

Groovy提供了一个简单的方法来执行命令行进程:

def process = "ls -l".execute()
println "Found text ${process.text}"

上述表达式将返回一个java.lang.Process实例,通过此实例,你可以访问in/out/err流以及返回值,比如:

def process = "ls -l".execute()
process.in.eachLine { line -> println line }

注意有很多命令是shell内置的,并且需要特殊的处理(比如Java),因此如果你要在windows主机上使用如下代码列出目录:

Process p = "dir".execute()
println "${p.text}"

你将捕获到IOException异常,提示信息可能是 “Cannot run program “dir”: CreateProcess error=2, The system cannot find the file specified.”

因此象这样写才行:

Process p = "cmd /c dir".execute()
println "${p.text}"
 
wiki/user_guide/input_output.txt · 最后更改: 2008-04-19 13:50 (外部编辑)
 
Recent changes RSS feed Creative Commons License Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki