Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a Reader to InputStream and a Writer to OutputStream?

Tags:

java

stream

Is there an easy way to avoid dealing with text encoding problems?

like image 789
Andrei Savu Avatar asked Sep 15 '08 11:09

Andrei Savu


People also ask

How do you write InputStream to OutputStream?

transferTo() Method. In Java 9 or higher, you can use the InputStream. transferTo() method to copy data from InputStream to OutputStream . This method reads all bytes from this input stream and writes the bytes to the given output stream in the original order.

How do I convert Inputstreamreader to InputStream?

2. Reader to InputStream in plain Java. In this example, first, we need to read all characters from given StringReader and aggregate them in StringBuilder . Then, using ByteArrayInputStream we create an instance of InputStream that wraps bytes array taken from String .

How do you convert InputStream to ByteArrayOutputStream?

You need to read each byte from your InputStream and write it to a ByteArrayOutputStream. You can then retrieve the underlying byte array by calling toByteArray(); e.g. ByteArrayOutputStream buffer = new ByteArrayOutputStream(); int nRead; byte[] data = new byte[16384]; while ((nRead = is. read(data, 0, data.


2 Answers

If you are starting off with a String you can also do the following:

new ByteArrayInputStream(inputString.getBytes("UTF-8")) 
like image 163
Ritesh Tendulkar Avatar answered Oct 07 '22 04:10

Ritesh Tendulkar


You can't really avoid dealing with the text encoding issues, but there are existing solutions in Apache Commons:

  • Reader to InputStream: ReaderInputStream
  • Writer to OutputStream: WriterOutputStream

You just need to pick the encoding of your choice.

like image 31
Peter Avatar answered Oct 07 '22 06:10

Peter