簡體   English   中英

帶有重音字符的 Java 屬性文件

[英]Java Properties File with accented characters

我正在嘗試從文本文件中加載屬性,但重音字符 (saül) 的編碼與 UTF-8 不同,如何避免它?

我的屬性文件有一個帶有重音字符 ( saül ) 的屬性。 當我遠程調試時,我發現properties.load(bufferedReader); 將其視為saül,因此當我寫入另一個文件時,它會被寫入saül ,我在應用程序的其他任何地方都有 UTF-8 編碼。 我不確定從文件中讀取屬性時我做錯了什么。

try {
    final String propertyFilePath = System.getProperty(JVM_ARGUMENT_NAME);
    if (StringUtils.hasText(propertyFilePath)) {
        setLocalOverride(true);
        resource = getApplicationContext().getResource(propertyFilePath);
        BufferedReader bufferedReader =
            new BufferedReader(new InputStreamReader(new FileInputStream(propertyFilePath), "UTF8"));
        properties.load(bufferedReader);
        externalFilePasswordConfigurer.afterPasswordPropertiesSet(properties);
        LOGGER.info("ExternalFilePropertyConfigurer UTF-8 Reader");
    }
    setProperties(properties);
    logProperties(properties);
} catch (Exception e) {
    LOGGER.error("ExternalFilePropertyConfigurer setter failed to set properties: ", e);
    throw new RuntimeException(e);
}

老問題,但據我所知,任何 .properties 文件都必須采用 ISO-8859-1 字符集,否則會出現問題。

當屬性文件中需要重音字符時,每個字符都必須替換為其 unicode 版本。 在這種特殊情況下, "saül" 必須更改為"sa\ül" ,其中"ü"

另一種解決方案是將文件類型從 .properties 更改為 .xml

請參閱此處的 java 文檔

load(Reader) / store(Writer, String) 方法以下面指定的簡單的面向行的格式從基於字符的流加載和存儲屬性。 load(InputStream) / store(OutputStream, String) 方法與 load(Reader)/store(Writer, String) 對的工作方式相同,除了輸入/輸出流以ISO 8859-1 字符編碼進行編碼 不能直接用這種編碼表示的字符可以使用 Java™ 語言規范第 3.3 節中定義的 Unicode 轉義來編寫; 轉義序列中只允許有一個 'u' 字符。 native2ascii 工具可用於將屬性文件與其他字符編碼相互轉換。

我知道這個問題很老,但我遇到了同樣的問題,不想將重音字符更改為其 unicode 編碼版本。

所以我在我的 pom.xml 中添加了以下插件

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>native2ascii-maven-plugin</artifactId>
    <version>2.0.1</version>
    <executions>
            <execution>
                    <goals>
                            <goal>resources</goal>
                    </goals>
                    <phase>process-resources</phase>
                    <configuration>
                            <srcDir>src/main/resources</srcDir>
                            <targetDir>${project.build.outputDirectory}</targetDir>
                            <encoding>${project.build.sourceEncoding}</encoding>
                            <includes>
                                    <include>message.properties</include>
                            </includes>
                    </configuration>
            </execution>
    </executions>
</plugin>

您可以在此處閱讀有關該插件的更多信息https://github.com/mojohaus/native2ascii-maven-plugin

暫無
暫無

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

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