How can I get a java.io.InputStream from a java.lang.String?

前端 未结 8 887
悲&欢浪女
悲&欢浪女 2020-12-23 20:23

I have a String that I want to use as an InputStream. In Java 1.0, you could use java.io.StringBufferInputStream, but that has been @Deprecra

8条回答
  •  忘掉有多难
    2020-12-23 20:33

    To my mind, the easiest way to do this is by pushing the data through a 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();
      }
    }
    

    The JVM implementation I'm using pushed data through in 8K chunks, but you could have some affect on the buffer size by reducing the number of characters written at one time and calling flush.


    An alternative to writing your own CharsetEncoder wrapper to use a Writer to encode the data, though it is something of a pain to do right. This should be a reliable (if inefficient) implementation:

    /** 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 buffer = new LinkedList();
      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);
        }
    
      }
    
    }
    

提交回复
热议问题