我有一个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实用程序库。
任何建议表示赞赏
用一个 Reader
使用字符串时。 InputStream
s实际上是用于二进制数据。
public Properties load(String propertiesString) {
Properties properties = new Properties();
properties.load(new StringReader(propertiesString));
return properties;
}
用一个 Reader
使用字符串时。 InputStream
s实际上是用于二进制数据。
public Properties load(String propertiesString) {
Properties properties = new Properties();
properties.load(new StringReader(propertiesString));
return properties;
}
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"))
尝试这个:
ByteArrayInputStream bais = new ByteArrayInputStream(propertiesString.getBytes("UTF-8"));
properties.load(bais);