我有一个String
我想用作InputStream
。在Java 1.0中,您可以使用java.io.StringBufferInputStream
,但那是@Deprecrated
(有充分的理由 - 您不能指定字符集编码):
此类未正确转换 字符到字节。从JDK 1.1开始, 创建流的首选方法 来自一个字符串是通过
StringReader
类。
您可以使用java.io.Reader
创建java.io.StringReader
,但没有适配器可以使用Reader
并创建InputStream
。
我找到了ancient bug要求合适的替代品,但据我所知,不存在这样的事情。
经常建议的解决方法是使用java.lang.String.getBytes()
作为java.io.ByteArrayInputStream
的输入:
public InputStream createInputStream(String s, String charset)
throws java.io.UnsupportedEncodingException {
return new ByteArrayInputStream(s.getBytes(charset));
}
但这意味着将内存中的整个String
表示为一个字节数组,并且无法实现流的目的。在大多数情况下,这不是什么大问题,但我正在寻找能够保留流意图的东西 - 尽可能少的数据在内存中实现(重新)。
答案 0 :(得分:77)
更新:这个答案正是OP不想要的。请阅读其他答案。
对于那些我们不关心在内存中重新实现数据的情况,请使用:
new ByteArrayInputStream(str.getBytes("UTF-8"))
答案 1 :(得分:18)
如果您不介意依赖commons-io包,则可以使用IOUtils.toInputStream(String text)方法。
答案 2 :(得分:4)
Apache Commons-IO有一个适配器,可以从Reader调整到InputStream,名为ReaderInputStream。
示例代码:
@Test
public void testReaderInputStream() throws IOException {
InputStream inputStream = new ReaderInputStream(new StringReader("largeString"), StandardCharsets.UTF_8);
Assert.assertEquals("largeString", IOUtils.toString(inputStream, StandardCharsets.UTF_8));
}
答案 3 :(得分:3)
在我看来,最简单的方法是通过Writer推送数据:
public class StringEmitter {
public static void main(String[] args) throws IOException {
class DataHandler extends OutputStream {
@Override
public void write(final int b) throws IOException {
write(new byte[] { (byte) b });
}
@Override
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
@Override
public void write(byte[] b, int off, int len)
throws IOException {
System.out.println("bytecount=" + len);
}
}
StringBuilder sample = new StringBuilder();
while (sample.length() < 100 * 1000) {
sample.append("sample");
}
Writer writer = new OutputStreamWriter(
new DataHandler(), "UTF-16");
writer.write(sample.toString());
writer.close();
}
}
我正在使用的JVM实现以8K块的形式推送数据,但是你可以通过减少一次写入的字符数并调用flush来对缓冲区大小产生一些影响。
编写自己的CharsetEncoder包装器以使用Writer对数据进行编码的替代方法,尽管做起来很麻烦。这应该是一个可靠的(如果效率低下)实现:
/** Inefficient string stream implementation */
public class StringInputStream extends InputStream {
/* # of characters to buffer - must be >=2 to handle surrogate pairs */
private static final int CHAR_CAP = 8;
private final Queue<Byte> buffer = new LinkedList<Byte>();
private final Writer encoder;
private final String data;
private int index;
public StringInputStream(String sequence, Charset charset) {
data = sequence;
encoder = new OutputStreamWriter(
new OutputStreamBuffer(), charset);
}
private int buffer() throws IOException {
if (index >= data.length()) {
return -1;
}
int rlen = index + CHAR_CAP;
if (rlen > data.length()) {
rlen = data.length();
}
for (; index < rlen; index++) {
char ch = data.charAt(index);
encoder.append(ch);
// ensure data enters buffer
encoder.flush();
}
if (index >= data.length()) {
encoder.close();
}
return buffer.size();
}
@Override
public int read() throws IOException {
if (buffer.size() == 0) {
int r = buffer();
if (r == -1) {
return -1;
}
}
return 0xFF & buffer.remove();
}
private class OutputStreamBuffer extends OutputStream {
@Override
public void write(int i) throws IOException {
byte b = (byte) i;
buffer.add(b);
}
}
}
答案 4 :(得分:2)
嗯,一种可能的方法是:
PipedOutputStream
PipedInputStream
PipedOutputStream
周围换OutputStreamWriter
(您可以在构造函数中指定编码)OutputStreamWriter
的任何内容都可以从PipedInputStream
中读取!当然,这似乎是一种相当神圣的做法,但至少它是一种方式。
答案 5 :(得分:1)
解决方案是推出自己的解决方案,创建一个InputStream
实现,可能会使用java.nio.charset.CharsetEncoder
将每个char
或char
块编码为一个字节数组必要时为InputStream
。
答案 6 :(得分:0)
我知道这是一个老问题,但我今天遇到了同样的问题,这是我的解决方案:
public static InputStream getStream(final CharSequence charSequence) {
return new InputStream() {
int index = 0;
int length = charSequence.length();
@Override public int read() throws IOException {
return index>=length ? -1 : charSequence.charAt(index++);
}
};
}
答案 7 :(得分:0)
您可以获得org.hsqldb.lib库的帮助。
public StringInputStream(String paramString)
{
this.str = paramString;
this.available = (paramString.length() * 2);
}