JAVA-ByteBuffer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • sweety mehra
    New Member
    • Nov 2006
    • 1

    #1

    JAVA-ByteBuffer

    How to convert ByteBuffer value into String
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by sweety mehra
    How to convert ByteBuffer value into String
    Which ByteBuffer implementation?
    What is the toString method returning?

    Comment

    • horace1
      Recognized Expert Top Contributor
      • Nov 2006
      • 1510

      #3
      Originally posted by sweety mehra
      How to convert ByteBuffer value into String
      It depends what you have stored in the ByteBuffer (ints, doubles, chars, etc). You get() the data and print print it appropriatly.

      e.g. the following puts a string a ByteBuffer then gets part of it back

      Code:
      // demo of byteBuffer
      import java.nio.*;
      
      class DemoByteBuffer{
        public static void main(String[] args){   
          String s="hello sam";
          System.out.println("s is " + s); 
          // convert String s to Bytes and warp in ByteBuffer buf
          ByteBuffer buf = ByteBuffer.wrap(s.getBytes());
          // convert another String to Bytes
          byte[] byte2 = (new String("hello tom").getBytes());
          System.out.println("byte2 is " + new String(byte2)); 
          // copy 3 bytes from buf position 6 to byte array position 6
          buf.position(6);
          buf.get(byte2, 6, 3);
          System.out.println("byte2 is " + new String(byte2)); 
        } 
      }
      when run gives
      s is hello sam
      byte2 is hello tom
      byte2 is hello sam

      A good discussion is at
      http://www.developer.c om/java/article.php/1449271

      Comment

      Working...