2
1

More than 3 years have passed since last update.

UTF-8で書かれたpropertiesファイルをGradleでnative2asciiする

Last updated at Posted at 2019-09-06

Windows環境でUTF-8で書かれたプロパティファイルをGradleでnative2asciiしたい。
Java9以降はpropertiesファイルはUTF-8で書けるのだけど、それ以前の環境向け。

結論

processReourcesのfilteringCharsetをUTF-8で指定して、filesMatchingでpropertiesファイルを指定する。

build.gradle
plugins {
  id: 'java'
}

tasks.withType(ProcessResources){
  filteringCharset = 'UTF-8'
  filesMatching('**/*.properties') {
     filter(org.apache.tools.ant.filters.EscapeUnicode)
  }
}

filteringCharsetはCopySpecで定義されていて、filterの時に使用する文字コードを指定できる。
antタスクのnative2asciiやJVMオプションの-Dfile.encodingを指定する例が多いがたぶんこちらが正攻法。

確認

下記のようなプロパティファイルをSJIS(MS932), UTF-8の両方で用意しておく

messages.properties
hello=こんにちは

filteringCharsetを指定しない場合

--- build/resources/main/sjis/messages.properties       2019-09-06 11:56:08.127830500 +0900
+++ build/resources/main/utf8/messages.properties       2019-09-06 11:56:08.138833400 +0900
@@ -1,2 +1,2 @@
-# encoding: sjis
-hello=\u3053\u3093\u306b\u3061\u306f
+# encoding: utf-8
+hello=\u7e3a\u8599\uff53\u7e3a\uff6b\u7e3a\uff61\u7e3a\uff6f
\ No newline at end of fil

SJISのほうがうまくUnicodeエスケープされている。
これはfilteringCharsetは既定ではJVMのシステムプロパティのfile.encodingを使用するため

filteringCharsetを指定した場合

--- build/resources/main/sjis/messages.properties       2019-09-06 11:34:18.501661300 +0900
+++ build/resources/main/utf8/messages.properties       2019-09-06 11:34:18.513667200 +0900
@@ -1,2 +1,2 @@
-# encoding: sjis
-hello=\ufffd\ufffd\ufffd\ufffd\u0242\ufffd\ufffd\ufffd
+# encoding: utf-8
+hello=\u3053\u3093\u306b\u3061\u306f
\ No newline at end of file

UTF-8のほうがうまくUnicodeエスケープされている

所感

ソースコードもリソースファイル類も実際はUTF-8でしかかかないから、javaのコンベンションプロパティで、このあたりのcharsetを全部UTF-8にしてもよいよね。

See

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1