LuxuryMode
LuxuryMode

Reputation: 33741

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?

Upvotes: 3

Views: 2876

Answers (4)

erickson
erickson

Reputation: 269717

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

Upvotes: 6

Dave G
Dave G

Reputation: 9777

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

Upvotes: 2

jzd
jzd

Reputation: 23629

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.

Upvotes: 0

DarinH
DarinH

Reputation: 4879

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.

Upvotes: 0

Related Questions