Home > database >  Java convert byte[] to InputStream with new line after each array entry
Java convert byte[] to InputStream with new line after each array entry

Time:09-07

Say I have a byte array like,

byte[] byteArray = { 'm', 'e', 'o', 'w'};

I'm converting this to InputStream using,

new ByteArrayInputStream(byteArray)

But I want the resultant InputStream to add a new line after each array entry like

m
e
o
w

How can I achieve this in an efficient way. The byte array could have 100s to 1000s of entries?

CodePudding user response:

The efficient way to do it would be to create another byte[]

byte[] byteArray = ...;
byte[] newBytes = new byte[byteArray.length *2];
for (int i = 0; i < byteArray.length; i  ) {
  newBytes[i*2] = byteArray[i];
  newBytes[i*2   1] = '\n';
}
  • Related