2017-07-14 3 views
0

ドイツ語の文字を16進値(00E4)にマップするプロパティファイルがあります。私は "iso-8859-1"でこのファイルをエンコードする必要がありました。ドイツ語の文字を表示する唯一の方法でした。私がしようとしているのは、ドイツ語を使い、文字列のどこにでもこれらの文字が現れているかどうか、そしてその値を16進形式に置き換えるかどうかを調べることです。例えば、ドイツのチャートを\u00E4に置き換えてください。プロパティファイルに " u"を書き込まないJava

コードは文字の罰金に置き換えられますが、1つのバックラッシュの代わりに、私は\\u00E4のようになります。私はコードで"\\u"を使用して、\uを試してみるのを見ることができますが、それは起こりません。私がここで間違っているところのアイデア?

private void createPropertiesMaps(String result) throws FileNotFoundException, IOException 
{ 
    Properties importProps = new Properties(); 
    Properties encodeProps = new Properties(); 

    // This props file contains a map of german strings 
    importProps.load(new InputStreamReader(new FileInputStream(new File(result)), "iso-8859-1")); 
    // This props file contains the german character mappings. 
    encodeProps.load(new InputStreamReader(
      new FileInputStream(new File("encoding.properties")), 
      "iso-8859-1")); 

    // Loop through the german characters 
    encodeProps.forEach((k, v) -> 
    { 
     importProps.forEach((key, val) -> 
     { 
      String str = (String) val; 

      // Find the index of the character if it exists. 
      int index = str.indexOf((String) k); 

      if (index != -1) 
      { 

       // create new string, replacing the german character 
       String newStr = str.substring(0, index) + "\\u" + v + str.substring(index + 1); 

       // set the new property value 
       importProps.setProperty((String) key, newStr); 

       if (hasUpdated == false) 
       { 
        hasUpdated = true; 
       } 
      } 

     }); 

    }); 

    if (hasUpdated == true) 
    { 
     // Write new file 
     writeNewPropertiesFile(importProps); 
    } 

} 

private void writeNewPropertiesFile(Properties importProps) throws IOException 
{ 
    File file = new File("import_test.properties"); 

    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); 

    importProps.store(writer, "Unicode Translations"); 

    writer.close(); 
} 
+0

「2つのようになっています。\ u00E4」それはタイプミスですか? 1つがあります。 – Michael

+0

それを指摘してくれてありがとう、ここでバックスラッシュをエスケープする必要があるようです。しかし、はい間違っている、別のバックスラッシュを意味していた。 –

答えて

2

重要な点は、単純なテキストファイルではなくJavaのプロパティファイルを作成することです。プロパティファイルでは、バックスラッシュ文字はエスケープ文字なので、プロパティ値にバックスラッシュが含まれていると、Javaはあなたのためにエスケープするのがとても親切です。

proertiesファイルとして読み込むことができるplianテキストファイルを書くことでJavaのプロパティファイルメカニズムを回避しようとするかもしれませんが、それはPropertiesによって自動的に提供されるすべてのフォーマットを行うことを意味します。クラスを手動で作成します。

+0

私のプロパティマップは、u = 00E4のようになります。だから私は新しい文字列を作成するときにのみそれを含めるので、バックラッシュはありません。私は、2つのバックスラッシュがあり、それを印刷するという事実を無視すると主張した。私は良い方法のように聞こえるので、あなたの方法をしばらく試してみると思います。どちらかを実装するのに時間がかかるべきではありません。 –

+0

しかし、新しい文字列はプロパティ値でもあり( 'importProps'に行きます)、保存時にエスケープされるバックスラッシュが1つ含まれています。 –

関連する問題