-2

When I try to add the strings to a bytebuffer, it doesn't write in the file. While I try to add int and double it is working fine. But for strings it doesn't work.

buffer.asCharBuffer().put(value.getValue1());
buffer.asCharBuffer().put(value.getValue2());
flotothemoon
  • 1,882
  • 2
  • 20
  • 37
Mohankumar
  • 11
  • 1
  • 2

2 Answers2

1
  1. Allocate a new ByteBuffer and set its size to a number large enough in order to avoid buffer to overflow when putting bytes to it
  2. Use the asCharBuffer() API method so as to be able to put characters directly into the byte buffer
  3. Using the put(String) API method we can put a String directly to the byte buffer

  4. The toString() API method returns the string representation of the ByteBuffer’s contents. Do not forget to flip() the ByteBuffer since the toString() API method displays ByteBuffer’s contents from the current buffer’s position on-wards:

UseByteBufferToStoreStrings:

import java.nio.ByteBuffer;
import java.nio.CharBuffer;
public class UseByteBufferToStoreStrings {

    public static void main(String[] args) {

        // Allocate a new non-direct byte buffer with a 50 byte capacity


    // set this to a big value to avoid BufferOverflowException
        ByteBuffer buf = ByteBuffer.allocate(50); 

        // Creates a view of this byte buffer as a char buffer
        CharBuffer cbuf = buf.asCharBuffer();

        // Write a string to char buffer
        cbuf.put("Your sting");

        // Flips this buffer.  The limit is set to the current position and then
        // the position is set to zero.  If the mark is defined then it is discarded
        cbuf.flip();

        String s = cbuf.toString();  // a string

        System.out.println(s);

    }

}

read more...

Nat
  • 3,587
  • 20
  • 22
Deepanshu J bedi
  • 1,530
  • 1
  • 11
  • 23
0

If you would like to add a String to a ByteBuffer using the return from it's getBytes() method works.

buf.put("Your string".getBytes); 
Duck_Triver
  • 3
  • 1
  • 3