Java: accessing a List of Strings as an InputStream

前端 未结 7 1577
情深已故
情深已故 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 12:00

    You can read from a ByteArrayOutputStream and you can create your source byte[] array using a ByteArrayInputStream.

    So create the array as follows:

     List source = new ArrayList();
     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();
    

    And reading from it is as simple as:

     InputStream in = new ByteArrayInputStream(bytes);
    

    Alternatively, depending on what you're trying to do, a StringReader might be better.

提交回复
热议问题