Java: accessing a List of Strings as an InputStream

前端 未结 7 1556
情深已故
情深已故 2021-02-05 11:24

Is there any way InputStream wrapping a list of UTF-8 String? I\'d like to do something like:

InputStream in = new XyzInputStream( List         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-05 11:53

    In short, no, there is no way of doing this using existing JDK classes. You could, however, implement your own InputStream that read from a List of Strings.

    EDIT: Dave Web has an answer above, which I think is the way to go. If you need a reusable class, then something like this might do:

    
    public class StringsInputStream> 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> in = new StringsInputStream>(source);
    
          int read = in.read();
          while (read != -1) {
             System.out.print((char) read);
             read = in.read();
          }
       }
    }
    
    

    This basically an adapter for ByteArrayInputStream.

提交回复
热议问题