Java:将字符串列表作为InputStream访问

Mar*_*zzi 15 java java-io

有没有办法InputStream包装UTF-8列表String?我想做点什么:

InputStream in = new XyzInputStream( List<String> lines )
Run Code Online (Sandbox Code Playgroud)

Dav*_*ebb 9

您可以从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可能会更好.


ben*_*phy 5

您可以将所有行连接在一起以创建一个 String ,然后使用将其转换为字节数组String#getBytes并将其传递给ByteArrayInputStream。然而,这并不是最有效的方法。


Jon*_*Jon 5

简而言之,不,没有办法使用现有的 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