Mark
Mark

Reputation: 141

Inserting a string into a bytebuffer

I am trying to write a bunch of integers and a string into the byte buffer. Later this byte array will be written to the hard drive. Everything seems to be fine except when I am writing the string in the loop only the last character is written. The parsing of the string appears correct as I have checked that. It appears to be the way I use the bbuf.put statement. Do I need to flush it after, and why does the .putInt statement work fine and not .put

//write the PCB from memory to file system
private static void _tfs_write_pcb()
{

    int c;
    byte[] bytes = new byte[11];


    //to get the bytes from volume name
    try {
        bytes = constants.filename.getBytes("UTF-8");           //convert to bytes format to pass to function
    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();
    }       

    ByteBuffer bbuf = ByteBuffer.allocate(bl_size);

    bbuf = bbuf.putInt(rt_dir_start);
    bbuf = bbuf.putInt(first_free_data_bl);
    bbuf = bbuf.putInt(num_bl_fat);
    bbuf = bbuf.putInt(bl_size);
    bbuf = bbuf.putInt(max_rt_entries);
    bbuf = bbuf.putInt(ft_copies);


    for (c=0; c < vl_name.length(); c++) {
        System.out.println((char)bytes[c]);
        bbuf = bbuf.put(bytes[c]);
    }

    _tfs_write_block(1, bbuf.array());

}

Upvotes: 1

Views: 4593

Answers (1)

guitarpicva
guitarpicva

Reputation: 441

ByteBuffer has a method for put'ting an array of byte. Is there a reason to put them one at a time? I note that put(byte) is abstract as well.

So the for loop is simplified to:

bbuf = bbuf.put(bytes, 6, bytes.length);

http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#put-byte:A-

EDIT: The Javadoc specifies that put(byte[]) begins at index 0, so use the form put(byte[], index, length) instead.

public final ByteBuffer put(byte[] src)

Relative bulk put method  (optional operation).

This method transfers the entire content of the given source byte array
into this buffer. An invocation of this method of the form dst.put(a) 
behaves in exactly the same way as the invocation

     dst.put(a, 0, a.length) 

Of course, it really should not matter HOW you insert the String bytes. I am just suggesting discovery experimentation.

Upvotes: 2

Related Questions