
import java.nio.*;
import java.nio.channels.*;
import java.io.*;
public class GetChannel {
private static final int BSIZE = 1024;
public static void main(String[] args) throws Exception {
// Write a file:
FileChannel fc =
new FileOutputStream("data.txt").getChannel();
fc.write(ByteBuffer.wrap("Some text ".getBytes()));
fc.close();
// Add to the end of the file:
fc =
new RandomAccessFile("data.txt", "rw").getChannel();
fc.position(fc.size()); // Move to the end
fc.write(ByteBuffer.wrap("Some more".getBytes()));
fc.close();
// Read the file:
fc = new FileInputStream("data.txt").getChannel();
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
fc.read(buff);
buff.flip();
while(buff.hasRemaining())
System.out.print((char)buff.get()); // 抽象方法为什么可以直接使用?
}
}
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
public static ByteBuffer allocate(int capacity) {
}
allocate实例化返回的是个HeapByteBuffer。
class HeapByteBuffer extends ByteBuffer
所以此处是父类的抽象方法调用具体的子类实例化的方法
查看源码可以知道
ByteBuffer buff = ByteBuffer.allocate(BSIZE);
这一步实例化了ByteBuffer的子类HeapByteBuffer
而在HeapByteBuffer里面get(int i)方法被重写了