火曜日, 12月 29, 2015

scala - ディレクトリのファイル操作

妻のパソコンの,とあるフォルダにある画像ファイルのタイムスタンプが何故かおかしくなってしまった.ファイルの数が膨大ということもあり,scalaでさっとコードを書いて修正した.

import java.io.File
import java.time.{LocalDateTime, ZoneId}
import java.util.Date

import org.apache.commons.io.FileUtils

/**
  * Created by neko32 on 2015/12/28.
  */
class FileDateChanger(preProcessDir:String, postProcessDir:String) {

  implicit def dateToLDate(d:Date):LocalDateTime = {
    d.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime()
  }

  def process(): Unit = {
    clean()
    val files = new File(preProcessDir).listFiles().filter(f => dateToLDate(new Date(f.lastModified())).getYear() == 2007)
    val totalNum = files.size
    var at = 0
    println(s"Total number of files - ${totalNum}")
    files.foreach { f =>
      var dat = new Date(f.lastModified())
      var f2 = new File(postProcessDir + "\\" + f.getName())
      println(s"processing .. ${f.getName()}[${new Date(f.lastModified())}]")
      FileUtils.copyFile(f, f2)
      f2.setLastModified(dat.plusYears(8).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli)
      println(s"to ${new Date(f2.lastModified())}")
      if(at % 10 == 0) println(s"processed ${at}")
      at += 1
    }
    println(s"done. # of processed files [${at}]")
  }

  private def clean(): Unit = {
    println(s"cleaning ${postProcessDir}")
    new File(postProcessDir).listFiles().foreach(_.delete())
    println("cleaning done.")
  }
}

object Runner {
  def main(args:Array[String]) = {
    val pre = "C:\\tmp\\pre_process"
    val post = "C:\\tmp\\post_process"
    new FileDateChanger(pre, post).process()
  }
}

0 件のコメント: