IOUtils.toByteArray deprecated - what can we use instead?

Viewed 5469

I am working on a spring boot application and needed to use toByteArray method provided by IOUtils, but it is deprecated. Is it safe to use string.getBytes() instead in a spring boot application or is there another way to get bytes from a text content?

2 Answers

Best is to use,

string.getBytes("UTF-8");

It is better to specify the encoding else default platform specific encoding may be used which may create unexpected results in case you have characters that can't be represented in default encoding like Arabic/Chinese/Hindi characters.

And UTF-8 is one of the best and compact encodings and covers over a million characters in other languages and emojis as well.

It's equivalent, for 2 reasons:

  • They claim it in the javadoc
  • If you look at the implementation:

    /** @deprecated */
    @Deprecated
    public static byte[] toByteArray(String input) throws IOException {
        return input.getBytes();
    }
    

getBytes() is actually called.

But it's not safe because it makes the assumption that you want the bytes in the platform's default charset. You should always specify a charset.

Related