30

I stole this snippet off the web. But it looks to be limited to 4096 bytes and is quite ugly IMO. Anyone know of a better approach? I'm actually using Groovy btw...

String streamToString(InputStream input) {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = input.read(b)) != -1;) {
            out.append(new String(b, 0, n));
        }
        return out.toString();
    }

EDIT:

I found a better solution in Groovy:

InputStream exportTemplateStream = getClass().getClassLoader().getResourceAsStream("export.template")
assert exportTemplateStream: "[export.template stream] resource not found"
String exportTemplate = exportTemplateStream.text
0

8 Answers 8

59

Some good and fast answers. However I think the best one is Groovy has added a "getText" method to InputStream. So all I had to do was stream.text. And good call on the 4096 comment.

Sign up to request clarification or add additional context in comments.

3 Comments

So you checked the docs after asking? At least you could paste an example of its use.
I continued looking after I asked of course, I didn't see the .text method at first. Here is the code snippet:InputStream exportTemplateStream = getClass().getClassLoader().getResourceAsStream("export.template") assert exportTemplateStream: "[export.template stream] resource not found" String exportTemplate = exportTemplateStream.text
fair enough. But as I've said to others: use the variant that takes an explicit character set -- the default character set is rarely what you want.
17

For Groovy

filePath = ... //< a FilePath object
stream = filePath.read() //< InputStream object

// Specify the encoding, and get the String object
//content = stream.getText("UTF-16") 
content = stream.getText("UTF-8") 

The InputStream class reference

The getText() without encoding, it will use current system encoding, ex ("UTF-8").

Comments

8

Try IOUtils from Apache Commons:

String s = IOUtils.toString(inputStream, "UTF-8");

Comments

5

It's reading the input in chunks of 4096 bytes(4KB), but the size of the actual string is not limited as it keeps reading more and appending it to the SringBuffer.

Comments

4

You can do it fairly easily using the Scanner class:

String streamToSring(InputStream input) {
    Scanner s = new Scanner(input);
    StringBuilder builder = new StringBuilder();
    while (s.hasNextLine()) {
        builder.append(s.nextLine() +"\n");
    }
    return builder.toString();
}

5 Comments

You need to pass a character set or you'll have a hard-to-diagnose bug.
@Anon, this code may have many bugs in it. Code is only presented as an example; not to be used in production.
@jinguy - does presenting buggy code "improve the internet"? Or simply add to rep?
@jinguy - if it hurts someone who comes along and takes the highest voted answer as written, I can't see how it would be improving the internet.
@Anon, my point is, people shouldn't be copying code off the internet as written and using it directly in their code.
2

That snippet has a bug: if the input uses a multi-byte character encoding, there's a good chance that a single character will span two reads (and not be convertable). And it also has the semi-bug that it relies on the platform's default encoding.

Instead, use Jakarta Commons IO. In particular, the version of IOUtils.toString() that takes an InputStream and applies an encoding to it.

Comments

1

For future reviewers who have similar problems, please note that both IOUtils from Apache, and Groovy's InputStream.getText() method require the stream to complete, or be closed before returning. If you are working with a persistent stream you will nead to deal with the "ugly" example that Phil originally posted, or work with non-blocking IO.

Comments

0

You can try something similar to this

new FileInputStream( new File("c:/tmp/file.txt") ).eachLine { println it }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.