问题 UTF-8将Java String编码为Properties


我有一个UTF-8编码的字符串,它是一串键+值对,需要加载到Properties对象中。我注意到我的初始实现中出现了乱码,经过一些谷歌搜索后我发现了这一点  这表明我的问题是什么 - 基本上默认使用ISO-8859-1属性。这个实现看起来像

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;
    }

没有指定编码,因此我的问题。至于我的问题,我无法弄清楚如何链接/创建一个 Reader / InputStream 组合传递给 Properties.load() 使用提供的 propertiesString 并指定编码。我认为这主要是由于我在I / O流方面缺乏经验以及java.io包中看似庞大的IO实用程序库。

任何建议表示赞赏


12683
2017-11-30 03:30


起源



答案:


用一个 Reader 使用字符串时。 InputStreams实际上是用于二进制数据。

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

13
2017-11-30 03:33



该构造函数不存在。 - BalusC
谢谢,我结帐了 StringReader,但我没有看到这样的构造函数。 - markdsievers
干杯马特,刚刚成功尝试了这个解决方案。最初没有使用StringReader导致我在寻找对编码的控制时遇到了问题。非常感谢您的帮助。 Upvote +接受我的朋友。 - markdsievers
你太客气了。抱歉最初指向一个不存在的构造函数。 - Matt Ball


答案:


用一个 Reader 使用字符串时。 InputStreams实际上是用于二进制数据。

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

13
2017-11-30 03:33



该构造函数不存在。 - BalusC
谢谢,我结帐了 StringReader,但我没有看到这样的构造函数。 - markdsievers
干杯马特,刚刚成功尝试了这个解决方案。最初没有使用StringReader导致我在寻找对编码的控制时遇到了问题。非常感谢您的帮助。 Upvote +接受我的朋友。 - markdsievers
你太客气了。抱歉最初指向一个不存在的构造函数。 - Matt Ball


   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"))

2
2017-12-13 12:46





尝试这个:

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

1
2017-11-30 03:36



我不得不用这个代替 StringReader 为了支持比android-9更早的Android SDK。 - Hans-Christoph Steiner