【发布时间】:2011-01-10 15:30:06
【问题描述】:
我正在使用LogManager.readConfiguration(),它需要一个我希望其内容来自字符串的 InputStream。是否存在未弃用的 StringBufferInputStream 等效项,例如 ReaderToInputStreamAdaptor?
【问题讨论】:
标签: java string inputstream deprecated
我正在使用LogManager.readConfiguration(),它需要一个我希望其内容来自字符串的 InputStream。是否存在未弃用的 StringBufferInputStream 等效项,例如 ReaderToInputStreamAdaptor?
【问题讨论】:
标签: java string inputstream deprecated
使用ByteArrayInputStream,并注意指定适当的字符编码。例如
ByteArrayInputStream(str.getBytes("UTF8"));
您需要考虑字符编码以确定每个字符如何转换为一组字节。请注意,您可以使用默认的 getBytes() 方法并通过 -Dfile.encoding=... 指定 JVM 运行时使用的编码
【讨论】:
readConfiguration() 将流传递给Properties#load(InputStream),该方法期望流为ISO-8859-1,而不是UTF-8。
String s = "test";
InputStream input = new ByteArrayInputStream(s.getBytes("UTF8"));
【讨论】:
readConfiguration() 将流传递给Properties#load(InputStream),该方法期望流为ISO-8859-1,而不是UTF-8。
LogManager.readConfiguration() 的文档说它接受java.util.Properties 格式的数据。所以,真正正确的编码安全实现是这样的:
String s = ...;
StringBuilder propertiesEncoded = new StringBuilder();
for (int i = 0; i < s.length(); i++)
{
char c = s.charAt(i);
if (c <= 0x7e) propertiesEncoded.append((char) c);
else propertiesEncoded.append(String.format("\\u%04x", (int) c));
}
ByteArrayInputStream in = new ByteArrayInputStream(propertiesEncoded.toString().getBytes("ISO-8859-1"));
编辑:编码算法已更正
EDIT2:其实java.util.Properties格式还有一些其他的限制(比如\和其他特殊字符的转义),见文档
EDIT3: 0x00-0x1f 转义被移除,正如 Alan Moore 所建议的那样
【讨论】:
s 是UTF-8,我相信这是正确的。
s 将只是一个字符串,在相同的编码中字符串总是使用 - 你不需要担心这个。你只需要知道 target 编码,正如@axtavt 所说的ISO-8859-1。