非弃用的StringBufferInputStream等价物

时间:2010-01-28 22:51:20

标签: java string inputstream deprecated

我正在使用LogManager.readConfiguration(),它需要一个InputStream,其内容我想来自一个字符串。是否有相应的StringBufferInputStream未被弃用,例如ReaderToInputStreamAdaptor

3 个答案:

答案 0 :(得分:8)

使用ByteArrayInputStream,并注意指定适当的字符编码。 e.g。

ByteArrayInputStream(str.getBytes("UTF8"));

您需要担心字符编码以确定每个字符如何转换为一组字节。请注意,您可以使用默认的getBytes()方法,并通过-Dfile.encoding=...指定JVM运行的编码

答案 1 :(得分:5)

请参阅java.io.ByteArrayInputStream

String s = "test";
InputStream input = new ByteArrayInputStream(s.getBytes("UTF8"));

答案 2 :(得分:3)

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建议