本文共 3206 字,大约阅读时间需要 10 分钟。
CharBuffer有一个toString()方法是这样定义的:“返回一个包含缓冲器中所有字符的字符串”。
public class BufferToText { private static final int BSIZE = 1024; public static void main(String[] args) throws Exception { FileChannel fc = new FileOutputStream("data3.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text".getBytes())); fc.close(); fc = new FileInputStream("data3.txt").getChannel(); ByteBuffer buff = ByteBuffer.allocate(BSIZE); fc.read(buff); buff.flip(); System.out.println(buff.asCharBuffer());//直接转化输出会乱码 buff.rewind();//倒带这个缓冲区。 位置设置为零,标记被丢弃。 String encoding = System.getProperty("file.encoding"); System.out.println("Deconded using " + encoding + ":" + Charset.forName(encoding).decode(buff));//按系统输入时的格式解码 fc = new FileOutputStream("data3.txt").getChannel(); fc.write(ByteBuffer.wrap("Some text".getBytes("UTF-16BE")));//输入时对其进行编码 fc.close(); fc = new FileInputStream("data3.txt").getChannel(); buff.clear(); fc.read(buff); buff.flip(); System.out.println(buff.asCharBuffer()); fc = new FileOutputStream("data3.txt").getChannel(); buff = ByteBuffer.allocate(500); buff.asCharBuffer().put("Some text");//转化成charBuffer再输入 fc.write(buff); fc.close(); fc = new FileInputStream("data3.txt").getChannel(); buff.clear(); fc.read(buff); buff.flip(); System.out.println(buff.asCharBuffer()); }}缓冲器荣啦的是普通的字节,为了把它们转化为字符串,我们要么在输入它们的时候对其进行编码,要么在将其从缓冲器输出时对它们进行解码。
尽管ByteBuffer只能保存字节类型的数据,但是它具有可以从其所容纳的字节中产生出各种不同基本类型值的方法。
public class GetData { private static final int BSIZE = 1024; public static void main(String[] args) { ByteBuffer bb = ByteBuffer.allocate(BSIZE); int i = 0; while (i++ < bb.limit()) if (bb.get() != 0) System.out.print("nonzero"); System.out.println("i = " + i); bb.rewind(); bb.asCharBuffer().put("Howdy!"); char c; while ((c = bb.getChar()) != 0) System.out.print(c + " "); System.out.println(); bb.rewind(); bb.asShortBuffer().put((short) 471142); System.out.println(bb.getShort()); bb.rewind(); bb.asIntBuffer().put(99471142); System.out.println(bb.getInt()); bb.rewind(); bb.asLongBuffer().put(99471142); System.out.println(bb.getLong()); bb.rewind(); bb.asFloatBuffer().put(99471142); System.out.println(bb.getFloat()); bb.rewind(); bb.asDoubleBuffer().put(99471142); System.out.println(bb.getDouble()); bb.rewind(); }}视图缓冲器可以让我们通过某个特定的基本数据类型的视窗查看其底层的ByteBuffer。ByteBuffer依然是实际存储数据的地方,“支持”着前面的视图。因此,对视图的任何修改都
会映射成为对ByteBuffer中数据的修改。
public class IntBufferDemo { private static final int BSIZE= 1024; public static void main(String[] args){ ByteBuffer bb=ByteBuffer.allocate(BSIZE); IntBuffer ib=bb.asIntBuffer(); ib.put(new int[]{ 11,42,47,99,143,811,1016}); System.out.println(ib.get(3)); ib.put(3,1811); ib.flip(); while (ib.hasRemaining()){ int i=ib.get(); System.out.println(i); } }}
转载地址:http://xmjqi.baihongyu.com/