21.11. charset の使用
charset オプションを使用すると、コンシューマーエンドポイントとプロデューサーエンドポイントの両方でファイルのエンコーディングを設定できます。たとえば、utf-8 ファイルを読み取り、ファイルを iso-8859-1 に変換する場合は、以下を実行できます。
from("file:inbox?charset=utf-8")
.to("file:outbox?charset=iso-8859-1")
from("file:inbox?charset=utf-8")
.to("file:outbox?charset=iso-8859-1")
ルートで convertBodyTo を使用することもできます。以下の例では、utf-8 形式の入力ファイルがありますが、ファイルの内容を iso-8859-1 形式でバイトアレイに変換します。その後、Bean にデータを処理させます。現在の charset を使用してコンテンツを送信トレイフォルダーに書き込む前。
from("file:inbox?charset=utf-8")
.convertBodyTo(byte[].class, "iso-8859-1")
.to("bean:myBean")
.to("file:outbox");
from("file:inbox?charset=utf-8")
.convertBodyTo(byte[].class, "iso-8859-1")
.to("bean:myBean")
.to("file:outbox");
コンシューマーエンドポイントで charset を省略すると、Camel はファイルの文字セットを認識せず、デフォルトでは UTF-8 を使用します。ただし、キー org.apache.camel.default.charset で異なるデフォルトエンコーディングを上書きして使用するように JVM システムプロパティーを設定できます。
以下の例では、ファイルが UTF-8 エンコーディングにない場合(ファイルを読み取るデフォルトのエンコーディング)が問題になる可能性があります。
この例では、ファイルを書き込む場合、コンテンツはすでにバイトアレイに変換されているため、コンテンツをそのまま直接書き込みます(それ以上のエンコーディングは必要ありません)。
from("file:inbox")
.convertBodyTo(byte[].class, "iso-8859-1")
.to("bean:myBean")
.to("file:outbox");
from("file:inbox")
.convertBodyTo(byte[].class, "iso-8859-1")
.to("bean:myBean")
.to("file:outbox");
鍵 Exchange.CHARSET_NAME を使用してエクスチェンジにプロパティーを設定することで、ファイルの書き込み時にエンコーディングを動的に上書きおよび制御することもできます。以下のルートでは、メッセージヘッダーの値で プロパティーを設定します。
from("file:inbox")
.convertBodyTo(byte[].class, "iso-8859-1")
.to("bean:myBean")
.setProperty(Exchange.CHARSET_NAME, header("someCharsetHeader"))
.to("file:outbox");
from("file:inbox")
.convertBodyTo(byte[].class, "iso-8859-1")
.to("bean:myBean")
.setProperty(Exchange.CHARSET_NAME, header("someCharsetHeader"))
.to("file:outbox");
同じエンコーディングでファイルを選択し、特定のエンコーディングでファイルを書き込む場合は、エンドポイントで charset オプションを使用することが推奨されます。
エンドポイントで charset オプションを明示的に設定している場合は、Exchange.CHARSET_NAME プロパティーに関係なく設定が使用されることに注意してください。
問題がある場合は、org.apache.camel.component.file で DEBUG ロギングを有効にし、特定の文字セットを使用してファイルを読み書きするときに Camel ログを有効にできます。
たとえば、以下のルートは以下をログに記録します。
from("file:inbox?charset=utf-8")
.to("file:outbox?charset=iso-8859-1")
from("file:inbox?charset=utf-8")
.to("file:outbox?charset=iso-8859-1")
ログは以下のようになります。
DEBUG GenericFileConverter - Read file /Users/davsclaus/workspace/camel/camel-core/target/charset/input/input.txt with charset utf-8 DEBUG FileOperations - Using Reader to write file: target/charset/output.txt with charset: iso-8859-1
DEBUG GenericFileConverter - Read file /Users/davsclaus/workspace/camel/camel-core/target/charset/input/input.txt with charset utf-8
DEBUG FileOperations - Using Reader to write file: target/charset/output.txt with charset: iso-8859-1