String conversion

gudii9
gudii9 used Ask the Experts™
on
which approach is better as given below and why. please advise


Convert with Plain Java
Let’s start with a simple example using Java to do the conversion – using an intermediary byte array:


@Test
public void givenUsingPlainJava_whenConvertingStringToInputStream_thenCorrect()
  throws IOException {
    String initialString = "text";
    InputStream targetStream = new ByteArrayInputStream(initialString.getBytes());
}
Note that the getBytes() method encodes this String using the platform’s default charset so to avoid undesirable behavior you can use getBytes(Charset charset) and control the encoding process.


 Convert with Commons IO
Finally, the Apache Commons IO library provides an excellent direct solution:


@Test
public void givenUsingCommonsIO_whenConvertingStringToInputStream_thenCorrect()
  throws IOException {
    String initialString = "text";
    InputStream targetStream = IOUtils.toInputStream(initialString);
}
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Software Engineer
Distinguished Expert 2018
Commented:
A lot of trouble is done to do as much as 0-copy as possible, IO systems, networking, (having headers already allocated in all IO buffers, so data doesn't need to be copied when being passed down through the network layers).

So solution 2 only copies once, that should be prefered.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial