如何从字符串数组创建输入流
我有一个字符串数组(实际上它是一个 ArrayList ),我想从中创建一个 InputStream ,数组的每个元素都是流中的一行。
我怎样才能以最简单、最有效的方式做到这一点?
I have an array of strings ( actually it's an ArrayList ) and I would like to create an InputStream from it, each element of the array being a line in the stream.
How can I do this in the easiest and most efficient way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用
StringBuilder
并将所有字符串附加到其中,并在其之间换行。 创建输入流然后使用new ByteArrayInputStream( builder.toString().getBytes("UTF-8") );
我在这里使用 UTF-8,但您可能必须使用不同的编码,取决于您的数据和要求。
另请注意,您可能必须包装该输入流才能逐行读取内容。
但是,如果您不必使用输入流,只需迭代字符串数组可能会更容易编码和更容易维护的解决方案。
You could use a
StringBuilder
and append all the strings to it with line breaks in between. Then create an input stream usingnew ByteArrayInputStream( builder.toString().getBytes("UTF-8") );
I'm using UTF-8 here, but you might have to use a different encoding, depending on your data and requirements.
Also note that you might have to wrap that input stream in order to read the content line by line.
However, if you don't have to use an input stream just iterating over the string array would probably the easiert to code and easier to maintain solution.
您可以尝试使用可以提供字节数组的 ByteArrayInputStream 类。但首先您必须将 List 转换为字节数组。尝试以下操作。
you can try using the class ByteArrayInputStream that you can give a byte array. But first you must convert you List to a byte array. Try the following.
最简单的方法可能是将它们在 StringBuilder 中粘合在一起,然后将生成的字符串传递给 StringReader。
The easiest might be to glue them together in a StringBuilder and then pass the resultant String to StringReader.
更好的方法是使用 BufferedWriter 类。
有一个样本:
The better way is use the BufferedWriter class.
There is one sample:
我这样做是因为您可以跳过一些复制,因此与 StringBuilder 方法相比是垃圾。
I am doing this since you can skip some copying and hence garbage vs the StringBuilder approach.