2015-11-03 12:00:44 -08:00
|
|
|
// newio/GetData.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-06-15 17:47:35 -07:00
|
|
|
// Getting different representations from a ByteBuffer
|
|
|
|
import java.nio.*;
|
|
|
|
|
|
|
|
public class GetData {
|
|
|
|
private static final int BSIZE = 1024;
|
|
|
|
public static void main(String[] args) {
|
|
|
|
ByteBuffer bb = ByteBuffer.allocate(BSIZE);
|
|
|
|
// Allocation automatically zeroes the ByteBuffer:
|
|
|
|
int i = 0;
|
|
|
|
while(i++ < bb.limit())
|
|
|
|
if(bb.get() != 0)
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println("nonzero");
|
|
|
|
System.out.println("i = " + i);
|
2015-06-15 17:47:35 -07:00
|
|
|
bb.rewind();
|
|
|
|
// Store and read a char array:
|
|
|
|
bb.asCharBuffer().put("Howdy!");
|
|
|
|
char c;
|
|
|
|
while((c = bb.getChar()) != 0)
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.print(c + " ");
|
|
|
|
System.out.println();
|
2015-06-15 17:47:35 -07:00
|
|
|
bb.rewind();
|
|
|
|
// Store and read a short:
|
|
|
|
bb.asShortBuffer().put((short)471142);
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(bb.getShort());
|
2015-06-15 17:47:35 -07:00
|
|
|
bb.rewind();
|
|
|
|
// Store and read an int:
|
|
|
|
bb.asIntBuffer().put(99471142);
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(bb.getInt());
|
2015-06-15 17:47:35 -07:00
|
|
|
bb.rewind();
|
|
|
|
// Store and read a long:
|
|
|
|
bb.asLongBuffer().put(99471142);
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(bb.getLong());
|
2015-06-15 17:47:35 -07:00
|
|
|
bb.rewind();
|
|
|
|
// Store and read a float:
|
|
|
|
bb.asFloatBuffer().put(99471142);
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(bb.getFloat());
|
2015-06-15 17:47:35 -07:00
|
|
|
bb.rewind();
|
|
|
|
// Store and read a double:
|
|
|
|
bb.asDoubleBuffer().put(99471142);
|
2015-11-03 12:00:44 -08:00
|
|
|
System.out.println(bb.getDouble());
|
2015-06-15 17:47:35 -07:00
|
|
|
bb.rewind();
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
i = 1025
|
|
|
|
H o w d y !
|
|
|
|
12390
|
|
|
|
99471142
|
|
|
|
99471142
|
|
|
|
9.9471144E7
|
|
|
|
9.9471142E7
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|