【JavaNIO】通道Channel

学习内容主要基于B站UP主,青空の霞光的视频,加上自己的理解。

通道

缓冲区具体应用在什么地方:通道

传统IO中,都是通过流进行传输,数据从流中不断流出。而在NIO中,数据放在缓冲区中进行管理,再使用通道将缓冲区中的数据传输到目的地。

通道接口层次

通道的根基是Channel

public interface Channel extends Closeable {
	// 通道是否处于开启状态
    public boolean isOpen();
	//用来关闭通道
    public void close() throws IOException;

}

一些子接口,首先读写操作:

public interface ReadableByteChannel extends Channel {
	//将通道中的数据读取到给定的缓冲区中
    public int read(ByteBuffer dst) throws IOException;
}
public interface WritableByteChannel extends Channel {
    //将给定缓冲区中的数据写入到通道中
    public int write(ByteBuffer src) throws IOException;
}

将读写功能整合为一个ByteChannel接口

public interface ByteChannel extends ReadableByteChannel, WritableByteChannel {

}

在这里插入图片描述
ByteChannel之下,还有很多派生接口

// 允许保留position和更改position的通道,以及对通道连接实体的相关操作
public interface SeekableByteChannel
    extends ByteChannel
{

    @Override
    int read(ByteBuffer dst) throws IOException;


    @Override
    int write(ByteBuffer src) throws IOException;

	//获取当前position
    long position() throws IOException;

	//修改当前position
    SeekableByteChannel position(long newPosition) throws IOException;

	//返回此通道连接到的实体的当前大小(比如文件大小)
    long size() throws IOException;

	//将此通道连接到的实体截断为给定大小
    SeekableByteChannel truncate(long size) throws IOException;
}

除了读写外,Channel还具有响应中断的能力

public interface InterruptibleChannel extends Channel
{

	//当其他线程调用此方法,在此通道上处于阻塞状态的线程会直接抛出AsynchronousCloseException异常
    public void close() throws IOException;

}
//InterruptibleChannel的抽象实现
public abstract class AbstractInterruptibleChannel
    implements Channel, InterruptibleChannel
{
	//加锁,关闭时使用
    private final Object closeLock = new Object();
    //当前channel的状态
    private volatile boolean open = true;

	
    protected AbstractInterruptibleChannel() { }

	//关闭操作
    public final void close() throws IOException {
        synchronized (closeLock) { //只有一个线程操作
            if (!open)
                return;
            open = false;
            implCloseChannel(); //开启关闭通道
        }
    }

	//该方法由close()调用,执行关闭通道的具体操作
    protected abstract void implCloseChannel() throws IOException;

    public final boolean isOpen() {
        return open;
    }


    // -- Interruption machinery --

    private Interruptible interruptor;
    private volatile Thread interrupted;

	// 开始阻塞。操作之前需要调用此方法进行标记
    protected final void begin() {
        if (interruptor == null) {
            interruptor = new Interruptible() {
                    public void interrupt(Thread target) {
                        synchronized (closeLock) {
                            if (!open)
                                return;
                            open = false;
                            interrupted = target;
                            try {
                                AbstractInterruptibleChannel.this.implCloseChannel();
                            } catch (IOException x) { }
                        }
                    }};
        }
        blockedOn(interruptor);
        Thread me = Thread.currentThread();
        if (me.isInterrupted())
            interruptor.interrupt(me);
    }
	//阻塞操作结束之后,也需要调用此方法。
    protected final void end(boolean completed)
        throws AsynchronousCloseException
    {
        blockedOn(null);
        Thread interrupted = this.interrupted;
        if (interrupted != null && interrupted == Thread.currentThread()) {
            interrupted = null;
            throw new ClosedByInterruptException();
        }
        if (!completed && !open)
            throw new AsynchronousCloseException();
    }


    // -- sun.misc.SharedSecrets --
    static void blockedOn(Interruptible intr) {         // package-private
        sun.misc.SharedSecrets.getJavaLangAccess().blockedOn(Thread.currentThread(),
                                                             intr);
    }
}

之后的实现类,都是基于这些接口定义的方法去实现的,比如FileChannel

在这里插入图片描述
上面就是通道相关的接口定义。


通道具体是如何使用的?比如将从输入流中读取数据然后打印出来

传统IO的写法

public static void main(String[] args) throws IOException {
    //用于存放数据
    byte[] data = new byte[10];
    //直接使用输入流
    InputStream in = System.in;

    while (true) {
        int len;
        while ((len = in.read(data)) >= 0) { //将输入流中的数据一次性读取到数组中
            System.out.println(new String(data, 0, len)); //读多少打印多少
        }
    }
}

使用通道后

public static void main(String[] args) throws IOException {
    //创建缓冲区
    ByteBuffer buffer = ByteBuffer.allocate(10);
    //输入,通过Channel读取数据,通过缓冲区装载数据
    ReadableByteChannel readChannel = Channels.newChannel(System.in);

    while (true) {
        //将通道中的数据写入到缓冲区中,缓冲区只有10个
        readChannel.read(buffer);
        //写入后,需要进行翻转,方便后面的读操作
        buffer.flip();
        //转换成String打印出来
        System.out.println("读取到一批数据:" + new String(buffer.array(), 0, buffer.remaining()));
        //回到最开始的状态
        buffer.clear();
    }
}

数据从Channel中读取得到,并通过缓冲区进行数据装载然后得到结果。

但是Channel不像流那样是单向的,而是双向传递的

文件传输FileChannel

在传统IO中,文件的写入和输出都是依靠FileOutputStreamFileInputStream完成的

public static void main(String[] args) {
    try(FileOutputStream out = new FileOutputStream("src/main/java/hello.txt")) {
        FileInputStream in = new FileInputStream("src/main/java/hello.txt");
        String data = "eeeeeewwwwww";
        out.write(data.getBytes()); //向文件输出流中写入数据,即将数据写入到文件中
        out.flush();

        byte[] bytes = new byte[in.available()];
        in.read();  //从文件输入流中读取文件的信息
        System.out.println(new String(bytes));

    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

而Channel只需要通过一个FileChannel就可以完成这两者的操作

public static void main(String[] args) throws IOException {
    //1.直接通过输入或输出流获取对应通道
    FileInputStream in = new FileInputStream("src/main/java/hello.txt");
    //获取文件通道
    FileChannel channel = in.getChannel();
    //创建一个容量为128的缓冲区
    ByteBuffer buffer = ByteBuffer.allocate(128);
    //将数据从通道读取到缓冲区中
    channel.read(buffer);

    //翻转一下
    buffer.flip();
    System.out.println(new String(buffer.array(), 0, buffer.remaining()));
}

通过输入流获取的文件通道读取没有问题,但是写入操作会报错NonWritableChannelException

public static void main(String[] args) throws IOException {
    //1.直接通过输入或输出流获取对应通道
    FileInputStream in = new FileInputStream("src/main/java/hello.txt");
    //
    FileChannel channel = in.getChannel();
    channel.write(ByteBuffer.wrap("hello".getBytes()));
}

FileOutputStream支持写操作,但不支持读操作

public static void main(String[] args) throws IOException {
    //1.直接通过输入或输出流获取对应通道
    FileOutputStream in = new FileOutputStream("src/main/java/hello.txt");
    //
    FileChannel channel = in.getChannel();
    channel.write(ByteBuffer.wrap("hello".getBytes()));
}

如何获取既可以读,又可以写的通道?

使用RandomAccessFile能支持文件的随机访问,并实现了数据流

public class RandomAccessFile implements DataOutput, DataInput, Closeable {

通过RandomAccessFile来创建通道,mode类型有:

  • r:只读
  • rw:读操作和写操作都可以
  • rws:每当进行写操作,同步刷新到磁盘,刷新内容和元数据
  • rwd:每当进行写操作,同步刷新到磁盘,刷新内容
public static void main(String[] args) throws IOException {
    try(RandomAccessFile f = new RandomAccessFile("test.txt", "")) {

    }
}

测试读写操作

public static void main(String[] args) throws IOException {
    try(RandomAccessFile f = new RandomAccessFile("test.txt", "rw")) {
        FileChannel channel = f.getChannel();
        channel.write(ByteBuffer.wrap("sdfrtewwer".getBytes()));

        System.out.println("写操作完成后文件访问位置:" + channel.position()); //读取从现在的位置开始
        channel.position(0); //将读取位置变为从文件的最开始

        ByteBuffer buffer = ByteBuffer.allocate(128);
        channel.read(buffer);
        buffer.flip();
        System.out.println(new String(buffer.array(), 0, buffer.remaining()));
    }
}

也可以对文件进行截断操作

public static void main(String[] args) throws IOException {
    try(RandomAccessFile f = new RandomAccessFile("test.txt", "rw")) {
        FileChannel channel = f.getChannel();
        //截断文件,只保留前20个字节
        channel.truncate(20);

        ByteBuffer buffer = ByteBuffer.allocate(128);
        channel.read(buffer);
        buffer.flip();
        System.out.println(new String(buffer.array(), 0, buffer.remaining()));
    }
}

如果要进行文件拷贝,只需要使用通道即可(transferTotransferFrom

public static void main(String[] args) throws IOException {
    try(FileOutputStream out = new FileOutputStream("test2.txt")) {
        FileInputStream in = new FileInputStream("test.txt");

        //获取test文件的通道
        FileChannel channel = in.getChannel();
        //直接将test文件通道中的数据传到test2文件通道中
        channel.transferTo(0, channel.size(), out.getChannel());
    }
}

要编辑某个文件时,使用MappedByteBuffer类,将其映射到内存中进行编辑,编辑的内容会同步更新到文件中

public static void main(String[] args) throws IOException {
    try(RandomAccessFile f = new RandomAccessFile("test.txt", "rw");) { //一定要可写
        FileChannel channel = f.getChannel();

        //从第4个字节开始,映射10个字节的内容到内存中
        MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_WRITE, 4, 10);

        //写入也是从pos开始的,默认从0开始,对应文件就是从第4个字节开始
        buffer.put("yyds".getBytes());

        //编辑完成后,通过force方法将数据写回文件的映射区域
        buffer.force();
    }
}

MappedByteBuffer使用直接缓冲区

文件锁FileLock

创建一个跨进程文件锁来防止多个进程之间的文件争抢。

FileLock是文件锁,保证同一时间只有一个进程能修改他,或都只读,这样解决了多进程间的同步文件,保证了安全性。

其是进程级别的,不是线程级别。可以解决多个进程并发访问同一个文件的问题,不适用于同一个进程中多个线程对一个文件的访问。

共享锁和独占锁:

  • 进程对文件加独占锁后,当前进程可对文件可读可写,其他进程无法对改文件进行读写操作
  • 进程对文件加共享锁后,进程可以对文件进行读操作,但是无法进行写操作。共享锁可以被多个进程添加,但只要存在共享锁,就不能添加独占锁
public static void main(String[] args) throws IOException, InterruptedException {

    RandomAccessFile f = new RandomAccessFile("test.txt", "rw");
    FileChannel channel = f.getChannel();
    System.out.println(new Date() + "正在尝试获取文件锁");

    //使用lock方式进行加锁
    //加锁操作支持对文件的某一段进行加锁,比如从0开始后的6个字节加锁,false表示是一把独占锁
    FileLock lock = channel.lock(0, 6, false); //true是共享锁
    System.out.println(new Date() + "已经获取到文件锁");

    Thread.sleep(5000); //处理5秒

    System.out.println(new Date() + "操作完毕,释放文件锁");
    lock.release();
}

除了使用lock()方法进行加锁外,也可以使用tryLock()方法以非阻塞方式获取文件锁,获取失败会得到null

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

    RandomAccessFile f = new RandomAccessFile("test.txt", "rw");
    FileChannel channel = f.getChannel();
    System.out.println(new Date() + "正在尝试获取文件锁");

    FileLock lock = channel.tryLock(0, Long.MAX_VALUE, false);
    System.out.println(lock);

    Thread.sleep(5000);
    lock.release();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值