Java Reference
In-Depth Information
Data Conversion
All data in Java ultimately resolves to bytes. Any primitive data type—
int
,
double
,
float
, etc.—can be written as bytes. Any sequence of bytes of the right length can be
interpreted as a primitive datum. For example, any sequence of four bytes corresponds
to an
int
or a
float
(actually both, depending on how you want to read it). A sequence
of eight bytes corresponds to a
long
or a
double
. The
ByteBuffer
class (and only the
ByteBuffer
class) provides relative and absolute put methods that fill a buffer with the
bytes corresponding to an argument of primitive type (except boolean) and relative and
absolute get methods that read the appropriate number of bytes to form a new primitive
datum:
public
abstract
char
getChar
()
public
abstract
ByteBuffer
putChar
(
char
value
)
public
abstract
char
getChar
(
int
index
)
public
abstract
ByteBuffer
putChar
(
int
index
,
char
value
)
public
abstract
short
getShort
()
public
abstract
ByteBuffer
putShort
(
short
value
)
public
abstract
short
getShort
(
int
index
)
public
abstract
ByteBuffer
putShort
(
int
index
,
short
value
)
public
abstract
int
getInt
()
public
abstract
ByteBuffer
putInt
(
int
value
)
public
abstract
int
getInt
(
int
index
)
public
abstract
ByteBuffer
putInt
(
int
index
,
int
value
)
public
abstract
long
getLong
()
public
abstract
ByteBuffer
putLong
(
long
value
)
public
abstract
long
getLong
(
int
index
)
public
abstract
ByteBuffer
putLong
(
int
index
,
long
value
)
public
abstract
float
getFloat
()
public
abstract
ByteBuffer
putFloat
(
float
value
)
public
abstract
float
getFloat
(
int
index
)
public
abstract
ByteBuffer
putFloat
(
int
index
,
float
value
)
public
abstract
double
getDouble
()
public
abstract
ByteBuffer
putDouble
(
double
value
)
public
abstract
double
getDouble
(
int
index
)
public
abstract
ByteBuffer
putDouble
(
int
index
,
double
value
)
In the world of new I/O, these methods do the job performed by
DataOutputStream
and
DataInputStream
in traditional I/O. These methods do have an additional ability
not present in
DataOutputStream
and
DataInputStream
. You can choose whether to
interpret the byte sequences as big-endian or little-endian
int
s,
float
s,
double
s, and
so on. By default, all values are read and written as big endian (i.e., most significant byte
first. The two
order()
methods inspect and set the buffer's byte order using the named
constants in the
ByteOrder
class. For example, you can change the buffer to little-endian
interpretation like so:
if
(
buffer
.
order
().
equals
(
ByteOrder
.
BIG_ENDIAN
))
{
buffer
.
order
(
ByteOrder
.
LITTLE_ENDIAN
);
}