[英]UTF-8 encoded Java String into Properties
I have a single UTF-8 encoded String that is a chain of key + value pairs that is required to be loaded into a Properties object. 我有一个UTF-8编码的字符串,它是一串键+值对,需要加载到Properties对象中。 I noticed I was getting garbled characters with my intial implementation and after a bit of googling I found this Question which indicated what my problem was - basically that Properties is by default using ISO-8859-1.
我注意到我的初始实现时出现乱码,经过一些谷歌搜索后,我发现这个问题表明我的问题是什么 - 基本上默认使用ISO-8859-1属性。 This implementation looked like
这个实现看起来像
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;
}
No encoding specified, hence my problem. 没有指定编码,因此我的问题。 To my question, I can't figure out how to chain / create a
Reader
/ InputStream
combination to pass to Properties.load()
that uses the provided propertiesString
and specifies the encoding. 对于我的问题,我无法弄清楚如何链接/创建
Reader
/ InputStream
组合以传递给使用提供的propertiesString
并指定编码的Properties.load()
。 I think this is mostly due to my inexperience in I/O streams and the seemingly vast library of IO utilities in the java.io package. 我认为这主要是由于我在I / O流方面缺乏经验以及java.io包中看似庞大的IO实用程序库。
Any advice appreciated. 任何建议表示赞赏
Use a Reader
when working with strings. 使用字符串时使用
Reader
。 InputStream
s are really meant for binary data. InputStream
实际上是用于二进制数据。
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;
}
then usage 用法
System.out.println(getProperties().getProperty("key"))
Try this: 尝试这个:
ByteArrayInputStream bais = new ByteArrayInputStream(propertiesString.getBytes("UTF-8"));
properties.load(bais);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.