Java: accessing a List of Strings as an InputStream

前端 未结 7 1701
情深已故
情深已故 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:52

    You can create some kind of IterableInputStream

    public class IterableInputStream extends InputStream {
    
        public static final int EOF = -1;
    
        private static final InputStream EOF_IS = new InputStream() {
            @Override public int read() throws IOException {
                return EOF;
            }
        };
    
        private final Iterator iterator;
        private final Function mapper;
    
        private InputStream current;
    
        public IterableInputStream(Iterable iterable, Function mapper) {
            this.iterator = iterable.iterator();
            this.mapper = mapper;
            next();
        }
    
        @Override
        public int read() throws IOException {
            int n = current.read();
            while (n == EOF && current != EOF_IS) {
                next();
                n = current.read();
            }
            return n;
        }
    
        private void next() {
            current = iterator.hasNext() 
                ? new ByteArrayInputStream(mapper.apply(iterator.next())) 
                : EOF_IS;
        }
    }
    

    To use it

    public static void main(String[] args) throws IOException {
        Iterable strings = Arrays.asList("1", "22", "333", "4444");
        try (InputStream is = new IterableInputStream(strings, String::getBytes)) {
            for (int b = is.read(); b != -1; b = is.read()) {
                System.out.print((char) b);
            }
        }
    }    
    

提交回复
热议问题