java - Guava equivalent for IOUtils.toString(InputStream) -


apache commons io has nice convenience method ioutils.tostring() read inputstream string.

since trying move away apache commons , guava: there equivalent in guava? looked @ classes in com.google.common.io package , couldn't find simple.

edit: understand , appreciate issues charsets. happens know sources in ascii (yes, ascii, not ansi etc.), in case, encoding not issue me.

you stated in comment on calum's answer going use

charstreams.tostring(new inputstreamreader(supplier.get(), charsets.utf_8)) 

this code problematic because overload charstreams.tostring(readable) states:

does not close readable.

this means inputstreamreader, , extension inputstream returned supplier.get(), not closed after code completes.

if, on other hand, take advantage of fact appear have inputsupplier<inputstream> , used overload charstreams.tostring(inputsupplier<r extends readable & closeable>), tostring method handle both creation , closing of reader you.

this jon skeet suggested, except there isn't overload of charstreams.newreadersupplier takes inputstream input... have give inputsupplier:

inputsupplier<? extends inputstream> supplier = ... inputsupplier<inputstreamreader> readersupplier =      charstreams.newreadersupplier(supplier, charsets.utf_8);  // inputstream , reader both created , closed in single call string text = charstreams.tostring(readersupplier); 

the point of inputsupplier make life easier allowing guava handle parts require ugly try-finally block ensure resources closed properly.

edit: personally, find following (which how i'd write it, breaking down steps in code above)

string text = charstreams.tostring(     charstreams.newreadersupplier(supplier, charsets.utf_8)); 

to far less verbose this:

string text; inputstreamreader reader = new inputstreamreader(supplier.get(),      charsets.utf_8); boolean threw = true; try {   text = charstreams.tostring(reader);   threw = false; } {   closeables.close(reader, threw); } 

which more or less you'd have write handle yourself.


edit: feb. 2014

inputsupplier , outputsupplier , methods use them have been deprecated in guava 16.0. replacements bytesource, charsource, bytesink , charsink. given bytesource, can contents string this:

bytesource source = ... string text = source.ascharsource(charsets.utf_8).read(); 

Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -