简体   繁体   English

stream to strings:将多个文件合并为一个字符串

[英]streams to strings: merging multiple files into a single string

I've got two text files that I want to grab as a stream and convert to a string. 我有两个文本文件,我想作为流抓取并转换为字符串。 Ultimately, I want the two separate files to merge. 最终,我希望合并两个单独的文件。

So far, I've got 到目前为止,我已经有了

     //get the input stream of the files. 

    InputStream is =
            cts.getClass().getResourceAsStream("/files/myfile.txt");


     // convert the stream to string

    System.out.println(cts.convertStreamToString(is));

getResourceAsStream doesn't take multiple strings as arguments. getResourceAsStream不会将多个字符串作为参数。 So what do I need to do? 那么我需要做什么? Separately convert them and merge together? 单独转换它们并合并在一起?

Can anyone show me a simple way to do that? 任何人都可以告诉我一个简单的方法吗?

It sounds like you want to concatenate streams. 听起来你想要连接流。 You can use a SequenceInputStream to create a single stream from multiple streams. 您可以使用SequenceInputStream从多个流创建单个流。 Then read the data from this single stream and use it as you need. 然后从该单个流中读取数据并根据需要使用它。

Here's an example: 这是一个例子:

String encoding = "UTF-8"; /* You need to know the right character encoding. */
InputStream s1 = ..., s2 = ..., s3 = ...;
Enumeration<InputStream> streams = 
  Collections.enumeration(Arrays.asList(s1, s2, s3));
Reader r = new InputStreamReader(new SequenceInputStream(streams), encoding);
char[] buf = new char[2048];
StringBuilder str = new StringBuilder();
while (true) {
  int n = r.read(buf);
  if (n < 0)
    break;
  str.append(buf, 0, n);
}
r.close();
String contents = str.toString();

Off hand I can think of a couple ways Create a StringBuilder, then convert each stream to a string and append to the stringbuilder. 我可以想到几个方法创建一个StringBuilder,然后将每个流转换为一个字符串并附加到stringbuilder。

Or, create a writable memorystream and stream each input stream into that memorystream, then convert that to a string. 或者,创建一个可写的内存流并将每个输入流流式传输到该内存流中,然后将其转换为字符串。

Create a loop that for each file loads the text into a StringBuilder . 创建一个循环,为每个文件将文本加载到StringBuilder Then once each file's data is appended, call toString() on the builder. 然后,在附加每个文件的数据后,在构建器上调用toString()。

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

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