Groovy는 입출력을 위한 여러가지
{link:지원 메서드|http://groovy.codehaus.org/groovy-jdk.html}{link} |
new File("foo.txt").eachLine { line -> println(line) }
|
어떠한 이유에서건 doSomething() 메서드가 예외를 던지면 eachLine() 메서드는 파일 자원을 닫아줍니다. 파일을 읽는 중에 예외가 발생해도 물론 자원이 제대로 닫힙니다.
Reader/Writer 혹은 InputStream/OutputStream을 사용하고자 한다면 클로저를 통해 접근할 수 있는 방법이 제공됩니다. 이 경우에도 물론 자원이 제대로 해제됩니다:
new File("foo.txt").withReader { reader ->
while (true) {
def line = reader.readLine()
}
}
|
Groovy는 명령행 프로세스를 실행하기 위한 간단한 방법을 제공합니다:
def process = "ls -l".execute()
println "Found text ${process.text}"
|
위 표현은 java.lang.Process 인스턴스를 반환하는데, 인스턴스는 in/out/err 스트림, 종료 코드(exit value) 등을 포함하고 있습니다:
def process = "ls -l".execute()
process.in.eachLine { line -> println line }
|