medium.png
iconv는 인코딩변환 유틸리티이다.
Unix/Linux, Cygwin을 사용하고 있다면 iconv를 이용하여 인코딩변환을 하지만
윈도우즈 사용자라면 변환이 용이치 않을 것이다.


다음은 그루비로 작성한 iconv 소스로 인코딩 변환을 쉽게 하자.

   1: #!/usr/bin/env groovy
   2:  
   3: if (args.size() < 2) {
   4:     println "Usage: iconv.groovy <from>:<enc> <to>:<enc>"
   5:     return
   6: }
   7:  
   8: def (from, fromEnc)= args[0].split(":")
   9: def (to, toEnc) = args[1].split(":")
  10:  
  11: new FileOutputStream(to).withWriter(toEnc) { writer ->
  12:     new FileInputStream(from).withReader(fromEnc) { reader ->
  13:         writer << reader
  14:     }
  15: }

코드설명

  • 8~9라인: 커맨드라인의 파라메터를 파싱한다.
    arg[0]는 ":"를 구분자로 쪼개어 from, fromEnc에 넣고 같은 방식으로 args[1]은 to, toEnc에 넣는다.
    이 방법은 그루비 1.6에서만 동작한다.
  • 15라인: to라는 이름의 파일을 열고 withWriter에서 toEnc 인코딩으로 클로저를 만든다.
  • 16라인: from파일을 열고 withReader에서 fromEnc 인코딩으로 읽어들이는 클로저를 만든다.
  • 17라인: 읽어들인 reader를 writer에 쓴다.

 

참고: John Flinchbaugh 블로그