Can I easily convert InputStream to BufferedReader using Guava?
I’m looking for something like:
InputStream inputStream = ...;
BufferedReader br = Streams.newBufferedReader(inputStream);
I can open files using the Files.newReader(File file, Charset charset). That’s cool and I want to do the same using the InputStream.
UPDATE:
Using CharStreams.newReaderSupplier seems to verbose for me. Correct me if I’m wrong, but in order to easily convert InputStream to BufferedReader using Guava I have to do something like that:
final InputStream inputStream = new FileInputStream("/etc/fstab");
Reader bufferedReader = new BufferedReader(CharStreams.newReaderSupplier(new InputSupplier<InputStream>(){
public InputStream getInput() throws IOException {
return inputStream;
}
}, Charset.defaultCharset()).getInput());
Of course I can create helper do sth like:
return new BufferedReader(new InputStreamReader(inputStream));
However I think that such helper should be offered by Guava IO. I can do such trick for File instance. Why cannot I for InputStream?
// Guava can do this
Reader r = Files.newReader(new File("foo"), charset);
// but cannot do this
Reader r = SomeGuavaUtil.newReader(inputStream, charset);
Correct me If I’m wrong but it seems to me like lack in the API.
No, there isn’t anything quite like that in Guava.
CharStreamsis the general class for working withReaders andWriters and it has a methodwhich could be useful with any kind of supplier of
InputStreams.Obviously, you can just write
new BufferedReader(new InputStreamReader(in, charset))or wrap that in your own factory method as well.Edit:
Yes, you wouldn’t want to use the
InputSupplierversion when you already have anInputStream. It’s sort of like how it’s a bad idea to make anIterablethat can actually only work once, such as one that wraps an existingIteratororEnumerationor some such. In general, usingInputSupplierrequires thinking about how you do I/O a little different, such as thinking of aFileas something that can act as a supplier ofFileInputStreams. I’ve usedInputSuppliers that wrap whole requests to a server and return the response content as anInputStream, enabling me to use Guava utilities to copy that to a file, etc.In any case, I’m not entirely sure why
CharStreamsdoesn’t have a method to create aReaderfrom anInputStreamother than perhaps they didn’t feel it was needed. You may want to file an issue requesting this.