有没有办法InputStream包装UTF-8列表String?我想做点什么:
InputStream in = new XyzInputStream( List<String> lines )
Run Code Online (Sandbox Code Playgroud)
您可以从a中读取,ByteArrayOutputStream然后可以byte[]使用a 创建源数组ByteArrayInputStream.
所以按如下方式创建数组:
List<String> source = new ArrayList<String>();
source.add("one");
source.add("two");
source.add("three");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (String line : source) {
baos.write(line.getBytes());
}
byte[] bytes = baos.toByteArray();
Run Code Online (Sandbox Code Playgroud)
阅读它就像这样简单:
InputStream in = new ByteArrayInputStream(bytes);
Run Code Online (Sandbox Code Playgroud)
或者,根据您要做的事情,StringReader可能会更好.
简而言之,不,没有办法使用现有的 JDK 类来做到这一点。但是,您可以实现自己的从字符串列表中读取的输入流。
编辑:戴夫·韦伯在上面有一个答案,我认为这是正确的方法。如果您需要一个可重用的类,那么可能会这样做:
public class StringsInputStream<T extends Iterable<String>> extends InputStream {
private ByteArrayInputStream bais = null;
public StringsInputStream(final T strings) throws IOException {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
for (String line : strings) {
outputStream.write(line.getBytes());
}
bais = new ByteArrayInputStream(outputStream.toByteArray());
}
@Override
public int read() throws IOException {
return bais.read();
}
@Override
public int read(byte[] b) throws IOException {
return bais.read(b);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return bais.read(b, off, len);
}
@Override
public long skip(long n) throws IOException {
return bais.skip(n);
}
@Override
public int available() throws IOException {
return bais.available();
}
@Override
public void close() throws IOException {
bais.close();
}
@Override
public synchronized void mark(int readlimit) {
bais.mark(readlimit);
}
@Override
public synchronized void reset() throws IOException {
bais.reset();
}
@Override
public boolean markSupported() {
return bais.markSupported();
}
public static void main(String[] args) throws Exception {
List source = new ArrayList();
source.add("foo ");
source.add("bar ");
source.add("baz");
StringsInputStream<List<String>> in = new StringsInputStream<List<String>>(source);
int read = in.read();
while (read != -1) {
System.out.print((char) read);
read = in.read();
}
}
}
这基本上是一个适配器ByteArrayInputStream。
| 归档时间: |
|
| 查看次数: |
20099 次 |
| 最近记录: |