簡體   English   中英

在UTF-8編碼的代碼中,使用帶重音符號的字符串,該字符串取自以ISO-8859-1編碼的文件

[英]In UTF-8 encoded code, use a string with accented characters taken from a file encoded in ISO-8859-1

有人提出了非常類似的問題,但我找不到解決方案。

我有一個屬性文件,即config.properties ,該文件以ISO-8859-1進行了以下編碼

config1 = some value with âccénted characters

我有一個加載屬性和一個獲取屬性值的方法

public class EnvConfig {
    private static final Properties properties = new Properties();

    static {        
        initPropertiesFromFile();
    }

    private static void initPropertiesFromFile() {
        InputStream stream;

        try {
            stream = EnvConfig.class.getResourceAsStream("/config/config.properties");
            properties.load(new InputStreamReader(stream, Charset.forName("ISO-8859-1")));
            // Tried that as well instead of the previous line: properties.load(stream);
        } catch (Exception e) {
            // Do something
        } finally {
            stream.close();
        }
    }

    public static String getProperty(String key, String defaultValue) {
        try {
            System.out.println(Charset.defaultCharset()); // Prints UTF-8
            // return new String(properties.getProperty(key).getBytes("ISO-8859-1")); // Returns some value with �cc�nted characters
            // return new String(properties.getProperty(key).getBytes("UTF-8")); // Returns some value with �cc�nted characters
            // return new String(properties.getProperty(key).getBytes("ISO-8859-1"), "UTF-8") // Returns some value with �cc�nted characters
            return properties.getProperty(key, defaultValue); // Returns some value with �cc�nted characters
        } catch (Exception e) {
            // Do something
            return defaultValue;
        }
    }
}

我有一些代碼可以對屬性值(字符串)進行處理,並且代碼需要帶有重音符號的正確字符串:有些值帶有點綴字符

public void doSomething() {
    ...
    EnvConfig.getProperty("config1"); // I need the exact same value as configured in the properties file: some value with âccénted characters; currently get some value with �cc�nted characters
    ...
}

項目位於UTF-8中(Java文件以UTF-8編碼),並且項目屬性/設置(pom)設置為UTF-8。

我缺少什么,我該如何實現? 我知道沒有“ UTF-8格式的字符串”之類的東西,因為字符串只是UTF-16代碼單元的序列。 但是, 如何在UTF-8編碼的代碼/項目中簡單地獲得相同的“可行”輸出,即在ISO-8859-1編碼的屬性文件中配置的帶重音的字符串?

經過數小時的搜索,事實證明我的編碼問題是由項目的POM中設置為true的資源過濾引起的:

    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>

將此設置為false可解決此問題。 我仍然需要找到一種使它在啟用過濾功能的情況下工作的方法,因此我將嘗試解決該問題。 在其他問題/答案中也有一些線索,例如激活資源過濾后的編碼錯誤 謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM