简体   繁体   中英

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. 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. 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();

You can utilize commons-io which has the ability to read a Stream into a String

http://commons.apache.org/io/api-release/org/apache/commons/io/IOUtils.html#toString%28java.io.InputStream%29

Off hand I can think of a couple ways Create a StringBuilder, then convert each stream to a string and append to the 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 . Then once each file's data is appended, call toString() on the builder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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