Groovy > ファイルの使い方
更新日
2016-03-05
広告
Groovyでファイルを処理する方法を紹介します。
一行ずつ処理
一行ずつ処理するには、eachLine メソッドを使います。サンプルファイル sample.dat の内容は以下のとおりです。My name is Taro.サンプル FileEachLine.groovy の内容は以下のとおりです。
def file = new File('sample.dat') file.eachLine { line -> print "${line} " } println ""各行を line という変数に代入し、出力しています。実行結果は、以下のようになります。
$ groovy FileEachLine My name is Taro.
ファイル名の取得
ファイル名def file = new File("./some/file.txt") def filename = file.getName()
ファイルに追記する方法
ファイルを開いて、appendメソッドを使います。def newFile = new File("hoge.txt") newFile.append("test line.\n")
広告
お問い合わせは sweng.tips@gmail.com まで。