Is there an easy way to avoid dealing with text encoding problems?
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.
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 .
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.
If you are starting off with a String you can also do the following:
new ByteArrayInputStream(inputString.getBytes("UTF-8"))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With