简体   繁体   中英

Is it possible to convert strongly-typed data to bytes using the ByteBuffer class?

Is it possible to convert strongly-typed data to bytes using the ByteBuffer class? If not, what is its main purpose? If yes, I am looking at its documentation and can find nothing. The put methods require a byte and not an int fro example.

as you might know, in computer programming most of the Data is somehow stored on the lower levels in Byte Format.

ByteBuffer =Convenient Read/Write of "all" Data Types to/from a Byte-Representation:

ByteBuffer is a very convenient Class to convert Bytes from types "like Int" to a Byte representation. But also the other way round. You can read "types" from a byte representation with the read methods.

Regarding your put Question: There is a generic put method that accepts a byte. But also a lot of convenience methods to put and read most of the standard datatypes, also int (as you asked):

http://download.oracle.com/javase/1,5.0/docs/api/java/nio/ByteBuffer.html#putInt(int )

ByteBuffer byteBuffer =  ByteBuffer.allocate(4);
byteBuffer.putInt(4);
byteBuffer.get() => gets the byte representation of the Int you put in 

Practical Use Case:

To be honest, the most heaviest use of ByteBuffer for me has been so far with Cassandra NoSQL DB. They store all the Data as byte(arrays) and ByteBuffer is a convenient Class to help to yout read and write those data.

High-End Usage:

As you can see the class is in NIO Package. I think the origin of ByteBuffer was to very very efficiently write Data for example to disk. It does not write it in memory before but directly maps a region of "blocks" on disk to the buffer in java. So it avoid any intermediate steps for reading and writing data to disk. But this is very highend usage...

Erm, you mean like ...

String foo = "My String";
ByteBuffer myBuffer = ByteBuffer.wrap(foo.getBytes());

EDIT: For an int you can do...

int i = 1234;
ByteBuffer b = ByteBuffer.allocate(4);
b.putInt(i);

Well, you can serialize your objects if they implement serializable and store the serialized bytes in a ByteBuffer if you really want to.

The main purpose of ByteBuffer appears to be buffering bytes, so that asynchronous transfers can be sped up.

It seems to be that you're thinking of getting the chunk of RAM where the object resides and placing that chunk into a ByteBuffer. This won't work. I mean, you could do it, but good luck getting the object back into a usable state. You have to do work on it, like turn the pointers into meaningful new addresses (referring to the places where you stored the actual fields of the object or whatnot). This is serializing, and this is what serializable does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM