かまたま日記3

プログラミングメイン、たまに日常

Groovy Tips集

よく忘れるのでいろいろな使い方をメモ
随時追記していきたい

ファイルに書き込む、ファイルを読み込む

final def TAB = '\t'
final LINE_SEPARATOR = System.getProperty("line.separator")
new File('hoge.tsv').withWriter { writer ->
	// ヘッダー
	writer.write('ID' + TAB + 'NAME' + LINE_SEPARATOR)
	// ボディ
	writer.write(1 + TAB + "kamatama_41")
}

new File('hoge.tsv').eachWithIndex { String line, int i ->
	// 1行目はヘッダなので処理しない
	if(i == 0) { return }
	assert line.split(TAB)[0].toInteger() == 1
	assert line.split(TAB)[1] == 'kamatama_41'
}

数値のコレクションの中で一番指定した数値に近い数値を取得する

def target = 2.8
def mostNearestNumber = [1,2,3,4,5].min {
	(target - it).abs()
}
assert mostNearestNumber == 3

正規表現による置換

def result = "2014-04-17 12:34:56".replaceAll(/[0-9]{4}-[0-9]{2}-[0-9]{2} ([0-9]{2}):([0-9]{2}):([0-9]{2})/, '$1$2$3').toInteger()
assert result == 123456