How to use UTF-8 in resource properties with ResourceBundle

后端 未结 16 2229
难免孤独
难免孤独 2020-11-22 03:28

I need to use UTF-8 in my resource properties using Java\'s ResourceBundle. When I enter the text directly into the properties file, it displays as mojibake.

16条回答
  •  粉色の甜心
    2020-11-22 03:56

    Here's a Java 7 solution that uses Guava's excellent support library and the try-with-resources construct. It reads and writes properties files using UTF-8 for the simplest overall experience.

    To read a properties file as UTF-8:

    File file =  new File("/path/to/example.properties");
    
    // Create an empty set of properties
    Properties properties = new Properties();
    
    if (file.exists()) {
    
      // Use a UTF-8 reader from Guava
      try (Reader reader = Files.newReader(file, Charsets.UTF_8)) {
        properties.load(reader);
      } catch (IOException e) {
        // Do something
      }
    }
    

    To write a properties file as UTF-8:

    File file =  new File("/path/to/example.properties");
    
    // Use a UTF-8 writer from Guava
    try (Writer writer = Files.newWriter(file, Charsets.UTF_8)) {
      properties.store(writer, "Your title here");
      writer.flush();
    } catch (IOException e) {
      // Do something
    }
    

提交回复
热议问题