1

The method below receives byte[] b of indeterminate length. It contains a string of characters to be printed to a console-style window. I would like to split b at the first line-feed character, so that that character is included in the first array. However, at the moment this throws an ArrayOutOfBoundsError, because stringBytes and extraBytes are declared with zero size. How can I get around this problem?

byte[] stringBytes = {};
byte[] extraBytes = {};
int i = 0;

while(i < b.length) {
    stringBytes[i] = b[i];
    if(b[i] == '\n' && i + 1 != b.length) {
        while(i < b.length) {
            extraBytes[i - stringBytes.length] = b[i++];
        }

        break;
    }

    i++;
}
3
  • 2
    You could convert the whole byte[] to a String and split the string on \n. Commented Mar 29, 2013 at 16:35
  • You'll have to initialize extraBytes after you know how long it will be. Commented Mar 29, 2013 at 16:35
  • Either initialize your arrays like this: byte[] stringBytes = new byte[b.length] and shrink the arrays later on or use Lists and transform those to arrays afterwards. Commented Mar 29, 2013 at 16:37

3 Answers 3

2

Try this:

byte[] stringBytes;
byte[] extraBytes;
int i = 0;

while(i < b.length) {
    if(b[i] == '\n' && i + 1 != b.length) {
        break;
    }

    i++;
}
stringBytes = java.util.Arrays.copyOf(b, i+1);
extraBytes = java.util.Arrays.copyOfRange(b, i+1, b.length - 1);
Sign up to request clarification or add additional context in comments.

Comments

1

I would rather build a String out of the bytes and use the String APIs.

However, if you really need to do the byte operations that you can declare stringBytes and extraBytes as List<Byte> such as you can add as many values as needed without knowing their size.

Comments

0

You can use a ByteArrayOutputStream as a light-weight expandable array of bytes:

  • To add a byte use the write method.
  • To get the bytes that you have written so far, use the toByteArray method.

For example:

ByteArrayOutputStream stringBytes = new ByteArrayOutputStream();
ByteArrayOutputStream extraBytes = new ByteArrayOutputStream();
int i = 0;

while(i < b.length) {
    stringBytes.write(b[i]);
    if(b[i] == '\n' && i + 1 != b.length) {
        i++;
        extraBytes.write(b, i, stringBytes.length - i);
        break;
    }
    i++;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.