网上资料大把,但要写写代码,我这个年纪的人才有一点点记忆了。。
参考URL:
http://blog.csdn.net/wuxianglong/article/details/6612282
package com.cg.io; import java.io.*; import java.nio.*; import java.nio.channels.*; public class TestIntBuffer { static private final byte message[] = {83, 111, 109, 101, 32, 98, 98}; static private String fileName = "d:\\hehehe\\test.txt"; public static void main(String[] args) throws Exception { FileOutputStream fout = new FileOutputStream(fileName); FileChannel fc = fout.getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); output("初始化", byteBuffer); for (int i=0; i<message.length; ++i) { byteBuffer.put(message[i]); } byteBuffer.flip(); output("调用flip()", byteBuffer); fc.write(byteBuffer); output("调用write()", byteBuffer); fout.close(); byteBuffer.clear(); output("调用clear()", byteBuffer); FileInputStream fin = new FileInputStream(fileName); fc = fin.getChannel(); fc.read(byteBuffer); output("调用read()", byteBuffer); byteBuffer.flip(); output("调用flip()", byteBuffer); while (byteBuffer.remaining() > 0) { byte b = byteBuffer.get(); System.out.print(((char)b)); } output("调用getChannel()", byteBuffer); byteBuffer.clear(); output("调用clear()", byteBuffer); fin.close(); IntBuffer intBuffer = IntBuffer.allocate(8); for (int i=0; i < intBuffer.capacity(); ++i) { int j = 2 * (i + 1); intBuffer.put(j); } intBuffer.flip(); while (intBuffer.hasRemaining()) { int j = intBuffer.get(); System.out.print(j + " "); } } public static void output(String step, Buffer buffer){ System.out.println(step + " : "); System.out.println("capacity: " + buffer.capacity() + ", "); System.out.println("position: " + buffer.position() + ", "); System.out.println("limit: " + buffer.limit() + ", "); System.out.println(); } }
时间: 2025-01-21 04:20:29