Open InputStream as Reader

Is it easy to convert an InputStream to a BufferedReader using Guava?

I am looking for something like:

 InputStream inputStream = ...; BufferedReader br = Streams.newBufferedReader(inputStream); 

I can open files using Files.newReader(File file, Charset charset) . This is cool, and I want to do the same with InputStream .

UPDATE:

Using CharStreams.newReaderSupplier seems CharStreams.newReaderSupplier to me. Correct me if I am wrong, but in order to easily convert InputStream to BufferedReader using Guava, I have to do something like this:

 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 a helper like:

 return new BufferedReader(new InputStreamReader(inputStream)); 

However, I believe that such an assistant should offer Guava IO. I can do such a trick for a File instance. Why can't I use 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 am wrong, but it seems to me that this is a flaw in the API.

+4
source share
1 answer

No, there is nothing like that in Guava. CharStreams is a general class for working with Reader and Writer , and it has a method

 InputSupplier<InputStreamReader> newReaderSupplier( InputSupplier<? extends InputStream> in, Charset charset) 

which may be useful to any InputStream s provider.

Obviously, you can simply write new BufferedReader(new InputStreamReader(in, charset)) or wrap this in your own factory method.

Edit:

Yes, you will not want to use the InputSupplier version if you already have an InputStream . It is like a bad idea to create an Iterable that can only work once, for example, one that wraps existing Iterator or Enumeration or some of them. In general, using InputSupplier requires thinking about how you do I / O a bit differently, for example, thinking of File as something that can act as a provider of FileInputStream s. I used InputSupplier , which terminates all requests to the server and returns the contents of the response as an InputStream , allowing me to use Guava utilities to copy this file, etc.

In any case, I'm not quite sure why CharStreams does not have a method of creating a Reader from an InputStream , except maybe they didn’t feel it was necessary. You might want to indicate a problem with the request.

+3
source

Source: https://habr.com/ru/post/1314645/


All Articles