ちなみに、1分割する毎にファイルを先頭から読み直しているため、分割する毎に処理が遅くなっていく。
行をスキップできればいいんだけど、途中で調べるのを辞めてしまった。。。
以下ソース
class FileUtils {
/**
* ファイルの行数を返却する
*
* @param filePath
* @param encode
* @return
*/
static def countLines(def filePath, def encode) {
def lineCount = 0
new File(filePath).eachLine(encode) { lineCount++ }
lineCount
}
/**
* 指定の行数にファイルを分割する
* 分割したファイルは分割元ファイルと同じディレクトリに書き出す
* @return
*/
static def splitFiles(def dstDir, def filePath, def encode, def lineSplitSize) {
// 行数を取得する
def lineSize = countLines(filePath, encode)
// 分割数を計算する
def splitSize = (lineSize / lineSplitSize).toInteger() + (lineSize % lineSplitSize == 0 ? 0 : 1)
println "総行数:${lineSize}/分割行数:${lineSplitSize}/分割ファイル数:${splitSize}"
// ファイルを分割する
(0..
def dstFile = new File("${dstDir}/${new File(filePath).name}.${idx}").withWriter(encode) { out ->
// 開始行数
def startLine = idx * lineSplitSize
def writeLines = 0
def start = new Date().time
try {
int procLine = 0
new File(filePath).eachLine(encode) { line ->
// 開始行に至ったら、内容を書き込む
if (procLine >= startLine) {
out << "${line}\n"
writeLines++
// 分割行数に至ったら、ループから抜ける
if (writeLines == lineSplitSize) {
throw new RuntimeException()
}
}
procLine++
}
} catch (e) {}
println "実行時間:${new Date().time - start}"
}
}
}
}