繁体   English   中英

如何从字符串数组创建 InputStream

[英]How to create an InputStream from an array of strings

我有一个字符串数组(实际上它是一个 ArrayList ),我想从中创建一个 InputStream ,数组的每个元素都是流中的一行。

我怎样才能以最简单和最有效的方式做到这一点?

您可以使用StringBuilder并将所有字符串附加到其中,并在其间添加换行符。 然后使用创建一个输入流

new ByteArrayInputStream( builder.toString().getBytes("UTF-8") );

我在这里使用 UTF-8,但您可能必须使用不同的编码,具体取决于您的数据和要求。

另请注意,您可能必须包装该输入流才能逐行读取内容。

但是,如果您不必使用输入流,只需遍历字符串数组可能更容易编码且更易于维护解决方案。

您可以尝试使用可以提供字节数组的类 ByteArrayInputStream。 但首先您必须将 List 转换为字节数组。 请尝试以下操作。

    List<String> strings = new ArrayList<String>();
    strings.add("hello");
    strings.add("world");
    strings.add("and again..");

    StringBuilder sb = new StringBuilder();
    for(String s : strings){
        sb.append(s);           
    }

    ByteArrayInputStream stream = new ByteArrayInputStream( sb.toString().getBytes("UTF-8") );
    int v = -1;
    while((v=stream.read()) >=0){
        System.out.println((char)v);
    }

我这样做是因为你可以跳过一些复制,因此垃圾与 StringBuilder 方法相比。

    public InputStream createInputStream(String ... strings){
        List<ByteArrayInputStream> streams = new ArrayList<>();
        for(String string: strings){
            streams.add(new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8)));
        }
        return new SequenceInputStream(Collections.enumeration(streams));
    }

最简单的方法可能是在 StringBuilder 中将它们粘合在一起,然后将结果字符串传递给 StringReader。

更好的方法是使用 BufferedWriter 类。 有一个示例:

try {
    List<String> list = new ArrayList<String>();
    BufferedWriter bf = new BufferedWriter(new FileWriter("myFile.txt"));

    for (String string : list) {
        bf.write(string);
        bf.newLine();
    }

    bf.close();
} catch (IOException ex) {
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM