Brian Graham Brian Graham - 5 months ago 20x
Java Question

Java: Remove first UTF string from byte array

I'm trying to remove a written string from a byte array and maintain the original separate objects:

byte[] data... // this is populated with the following:
// 00094E6966747943686174001C00074D657373616765000B4372616674656446757279000474657374
// to string using converter : " ChannelMessageUsernametest"
// notice that tab/whitespace, ignore quotes
// The byte array was compiled by writing the following (writeUTF from a writer):
// Channel
// Message
// Username
// test

Now I'm trying to strip
from the byte array:

ByteArrayDataInput input = ByteStreams.newDataInput(message);
String channel = input.readUTF(); // Channel, don't want this
String message = input.readUTF(); // Message
// works good, but I don't want Channel,
// and I can't remove it from the data before it arrives,
// I have to work with what I have

Here is my problem:

byte[] newData = Arrays.copyOfRange(data, channel.length() + 2, data.length)
// I use Arrays.copyOfRange to strip the whitespace (I assume it's not needed)
// As well, since it's inclusive of length size, I have to add 1 more,
// resulting in channel.length() + 1
// ...
ByteArrayDataInput newInput = ByteStreams.newDataInput(message);
String channel = newInput.readUTF(); // MessageUsernametext

See how I lose the separation of the objects, how can I keep the original "sections" of objects in the original
byte[] data
byte[] newData

  • It's safe to assume that
    String channel
    (before and after stripping) is a string

  • It's NOT safe to assume that every object is a string, assume everything is random, because it is


As long as you can guarantee that channel is always in a reasonable character range (for example alphanumeric), changing the channel.length() + 2 to channel.length() + 4 should be sufficient.