您的浏览器过于古老 & 陈旧。为了更好的访问体验, 请 升级你的浏览器
Ready 发布于2013年08月14日 12:40

原创 Java nio入门教程详解(十)

2004 次浏览 读完需要≈ 7 分钟

内容目录

2.4.4 数据元素视图

ByteBuffer 类提供了一个不太重要的机制来以多字节数据类型的形式存取byte数据组。ByteBuffer类为每一种原始数据类型提供了存取的和转化的方法:

public abstract class ByteBuffer extends Buffer implements Comparable
{
public abstract char getChar();
public abstract char getChar (int index);
public abstract short getShort();
public abstract short getShort (int index);
public abstract int getInt();
public abstract int getInt (int index);
public abstract long getLong();
public abstract long getLong (int index);
public abstract float getFloat();
public abstract float getFloat (int index);
public abstract double getDouble();
public abstract double getDouble (int index);
public abstract ByteBuffer putChar (char value);
public abstract ByteBuffer putChar (int index, char value);
public abstract ByteBuffer putShort (short value);
public abstract ByteBuffer putShort (int index, short value);
public abstract ByteBuffer putInt (int value);
public abstract ByteBuffer putInt (int index, int value);
public abstract ByteBuffer putLong (long value);
public abstract ByteBuffer putLong (int index, long value);
public abstract ByteBuffer putFloat (float value);
public abstract ByteBuffer putFloat (int index, float value);
public abstract ByteBuffer putDouble (double value);
public abstract ByteBuffer putDouble (int index, double value);
}

这些函数从当前位置开始存取ByteBuffer的字节数据,就好像一个数据元素被存储在那里一样。根据这个缓冲区的当前的有效的字节顺序,这些字节数据会被排列或打乱成需要的原始数据类型。比如说,如果getInt()函数被调用,从当前的位置开始的四个字节会被包装成一个int类型的变量然后作为函数的返回值返回。参见 2.4.1 节。

假设一个叫buffer的ByteBuffer对象处于图 Figure 2-17 的状态。

图 2-17. 包含一些数据的 ByteBuffer

这段代码:

int value = buffer.getInt();

会返回一个由缓冲区中位置1-4的byte数据值组成的int型变量的值。实际的返回值取决于缓冲区的当前的比特排序(byte-order)设置。更具体的写法是:

int value = buffer.order (ByteOrder.BIG_ENDIAN).getInt();

这将会返回值 0x3BC5315E,同时:

int value = buffer.order (ByteOrder.LITTLE_ENDIAN).getInt();

返回值 0x5E31C53B。 如果您试图获取的原始类型需要比缓冲区中存在的字节数更多的字节,会抛出BufferUnderflowException。对于图 Figure2-17 中的缓冲区,这段代码会抛出异常,因为一个long型变量是8个字节的,但是缓冲区中只有5个字节:

long value = buffer.getLong();

这些函数返回的元素不需要被任何特定模块界限所限制。数值将会从以缓冲区的当前位置开始的字节缓冲区中取出并组合,无论字组是否对齐。这样的做法是低效的,但是它允许对一个字节流中的数据进行随机的放置。对于从二进制文件数据或者包装数据成特定平台的格式或者导出到外部的系统,这将是非常有用的。

put 函数提供与 get 相反的操作。原始数据的值会根据字节顺序被分拆成一个个byte数据。如果存储这些字节数据的空间不够,会抛出BufferOverflowException

每一个函数都有重载的和无参数的形式。重载的函数对位置属性加上特定的字节数。然后无参数的形式则不改变位置属性。

Java nio入门教程详解(十一)

  • CodePlayer技术交流群1
  • CodePlayer技术交流群2

0 条评论

撰写评论