2011-11-30 7 views
11

プロパティオブジェクトにロードする必要があるキーと値のペアのチェーンである単一のUTF-8エンコードされたStringがあります。私は最初のインプリメンテーションで文字化けしていることに気付きました。ちょっとしたグーグルで私はこの問題が何であるかを示すQuestionを見つけました - 基本的にプロパティはISO-8859-1を使っています。この実装は次のように見えますプロパティにUTF-8エンコードされたJava String

public Properties load(String propertiesString) { 
     Properties properties = new Properties(); 
     try { 
      properties.load(new ByteArrayInputStream(propertiesString.getBytes())); 
     } catch (IOException e) { 
      logger.error(ExceptionUtils.getFullStackTrace(e)); 
     } 
     return properties; 
    } 

エンコーディングが指定されていないため、私の問題です。私の質問には、/InputStreamの組み合わせをProperties.load()に渡し、提供されたpropertiesStringを使用してエンコーディングを指定する方法を見つけることができません。これは主にI/Oストリームの不慣れさと、java.ioパッケージのIOユーティリティの膨大なライブラリによるものだと思います。

アドバイスありがとうございます。

答えて

13

文字列を操作する場合はReaderを使用してください。 InputStreamは実際にバイナリデータを意味します。

public Properties load(String propertiesString) { 
    Properties properties = new Properties(); 
    properties.load(new StringReader(propertiesString)); 
    return properties; 
} 
+0

それコンストラクタが存在しません。 – BalusC

+0

ありがとう、私はcheckout [StringReader](http://docs.oracle.com/javase/6/docs/api/java/io/StringReader.html)でしたが、そのようなコンストラクタは見当たりませんでした。 – markdsievers

+0

乾杯Mattは、このソリューションをうまく試しました。最初にStringReaderを使用しなかったのは、私の目隠しがエンコーディングのコントロールを探していたからです。ご協力いただきありがとうございます。アップフォート+あなたのために私の友人を受け入れる。 – markdsievers

1

これを試してみてください:

ByteArrayInputStream bais = new ByteArrayInputStream(propertiesString.getBytes("UTF-8")); 
properties.load(bais); 
+1

アンドロイド-9より古いAndroid SDKをサポートするために、 'StringReader'の代わりにこれを使用しなければなりませんでした。 –

1
private Properties getProperties() throws IOException { 
     ClassLoader classLoader = getClass().getClassLoader(); 
     InputStream input = classLoader.getResourceAsStream("your file"); 
     InputStreamReader inputStreamReader = new InputStreamReader(input, "UTF-8"); 
     Properties properties = new Properties(); 
     properties.load(inputStreamReader); 
     return properties; 
    } 

、その後の使用

System.out.println(getProperties().getProperty("key")) 
関連する問題