代码之家  ›  专栏  ›  技术社区  ›  Kaleb Pederson

不推荐使用的StringBufferInputStream等效项

  •  12
  • Kaleb Pederson  · 技术社区  · 16 年前

    我正在和 LogManager.readConfiguration() 它需要一个inputstream,我希望它的内容来自一个字符串。有等价物吗 StringBufferInputStream 这不是不赞成的,例如 ReaderToInputStreamAdaptor ?

    3 回复  |  直到 16 年前
        1
  •  3
  •   axtavt    16 年前

    文件 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属性 格式还有一些其他限制(例如转义 \ 以及其他特殊字符),参见文档

    EdTe3: 根据艾伦·摩尔的建议,0x00-0x1F转义被移除。

        2
  •  8
  •   Brian Agnew    16 年前

    使用 ByteArrayInputStream ,并注意指定适当的字符编码。例如

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

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

        3
  •  5
  •   Kevin    16 年前

    参见 java.io.ByteArrayInputStream

    String s = "test";
    InputStream input = new ByteArrayInputStream(s.getBytes("UTF8"));
    
    推荐文章