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

前端 未结 8 816
悲&欢浪女
悲&欢浪女 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:54

    I know this is an old question but I had the same problem myself today, and this was my solution:

    public static InputStream getStream(final CharSequence charSequence) {
     return new InputStream() {
      int index = 0;
      int length = charSequence.length();
      @Override public int read() throws IOException {
       return index>=length ? -1 : charSequence.charAt(index++);
      }
     };
    }
    
    0 讨论(0)
  • 2020-12-23 20:57

    There is an adapter from Apache Commons-IO which adapts from Reader to InputStream, which is named ReaderInputStream.

    Example code:

    @Test
    public void testReaderInputStream() throws IOException {
        InputStream inputStream = new ReaderInputStream(new StringReader("largeString"), StandardCharsets.UTF_8);
        Assert.assertEquals("largeString", IOUtils.toString(inputStream, StandardCharsets.UTF_8));
    }
    

    Reference: https://stackoverflow.com/a/27909221/5658642

    0 讨论(0)
提交回复
热议问题