未弃用的 StringBufferInputStream 等效项

发布于 2024-08-19 16:49:50 字数 419 浏览 4 评论 0原文

我正在使用 LogManager.readConfiguration() 需要一个输入流,我希望其内容来自字符串。是否有相当于 StringBufferInputStream 尚未弃用,例如 ReaderToInputStreamAdaptor

I'm working with LogManager.readConfiguration() which requires an InputStream whose contents I'd like to come from a string. Is there an equivalent of StringBufferInputStream that's not deprecated, such as a ReaderToInputStreamAdaptor?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

蓝眸 2024-08-26 16:49:50

使用ByteArrayInputStream,并且要小心指定适当的字符编码。例如,

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

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

Use the ByteArrayInputStream, and be careful to specify an appropriate character encoding. e.g.

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

You need to worry about the character encoding to determine how each character is converted to a set of bytes. Note you can use the default getBytes() method and specify the encoding the JVM runs with via -Dfile.encoding=...

窝囊感情。 2024-08-26 16:49:50

请参阅 java.io.ByteArrayInputStream

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

See java.io.ByteArrayInputStream

String s = "test";
InputStream input = new ByteArrayInputStream(s.getBytes("UTF8"));
-黛色若梦 2024-08-26 16:49:50

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

编辑:编码算法更正

编辑2:实际上,java.util.Properties格式有一些其他限制(例如 \ 和其他特殊字符的转义),请参阅文档

EDIT3: 0x00-0x1f 转义已删除,正如 Alan Moore 建议的那样

Documentation of LogManager.readConfiguration() says that it accepts data in java.util.Properties format. So, the really correct encoding-safe implementation is this:

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

EDIT: Encoding algorithm corrected

EDIT2: Actually, java.util.Properties format have some other restrictions (such as escaping of \ and other special characters), see docs

EDIT3: 0x00-0x1f escaping removed, as Alan Moore suggests

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文