java nio 类图_Java NIO原理剖析之 磁盘IO

网络上有很多写NIO的文章, 但是大多讲的网络那一块, 我想像前俩次那样先从磁盘IO讲起, 然后慢慢过渡到网络IO, 再慢慢地进入socket, epoll, 能有这样一个循序渐进的过程.

仍然从一个读文件的小demo程序开始入手分析

public class TestFileChannel {

public static void main(String[] args) throws IOException {

FileInputStream inputStream = new FileInputStream("./10bytes.txt");

FileChannel channel = inputStream.getChannel();

// 分配一个10byte的ByteBuffer.ByteBuffer byteBuffer = ByteBuffer.allocate(10);

channel.read(byteBuffer);

// TODO close}

}

看一下getChannel()实现

public FileChannel getChannel() {

synchronized (this) {

if (channel == null) {

channel = FileChannelImpl.open(fd, path, true, false, this);

}

return channel;

}

}

getChannel()的源码很简单, 就是直接生成了一个FileChannelImpl实例

// 下列内容在openjdk-jdk8u-jdk8u/jdk/src/share/classes/sun/nio/ch/FileChannelImpl.java

// Used by FileInputStream.getChannel() and RandomAccessFile.getChannel() public static FileChannel open(FileDescriptor fd, String path,

boolean readable, boolean writable,

Object parent)

{

return new FileChannelImpl(fd, path, readable, writable, false, parent);

}

通过上面的UML类图, 可以看到FileChannel主要是定义了一些抽象方法, 真正的读写实现是在FileChannelImpl中实现的.

// 下列内容在openjdk-jdk8u-jdk8u/jdk/src/share/classes/sun/nio/ch/FileChannelImpl.java

public int read(ByteBuffer dst) throws IOException {

ensureOpen();

if (!readable)

throw new NonReadableChannelException();

synchronized (positionLock) {

int n = 0;

int ti = -1;

try {

begin();

ti = threads.add();

if (!isOpen())

return 0;

do {

n = IOUti

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值