通过Channel及Buffer实现多线程读取文件

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.Callable;


public class MyTask implements Callable<ByteBuffer> {
    //position用于表示线程从哪开始读取文件
    private long position;
    private FileChannel inchannel;

    public MyTask(FileChannel inchannel , long position) {
        this.position = position;
        this.inchannel = inchannel;
    }

    @Override
    public ByteBuffer call() throws Exception {
        //创建一个1024 * 8大小缓存区
        ByteBuffer buffer = ByteBuffer.allocate(1024 * 8);
        inchannel.read(buffer , position);

        System.out.println(Thread.currentThread().getName() + "正在工作");
        //将读取完成的缓存区返回
        return buffer;
    }

}

import org.junit.Test;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.concurrent.*;

import static java.util.concurrent.Executors.*;

public class TEST {
    @Test
    public void test1() throws Exception {
        //读取的文件通道
        FileChannel inChannel = new RandomAccessFile("Z:\\勤奋蜂\\1.jpg", "r").getChannel();
        //写入的文件通道
        FileChannel outChannel = new RandomAccessFile("Z:\\勤奋蜂\\2.jpg", "rw").getChannel();
        try{
            //计算需要多少个1024 * 8的缓存区,就建立几个线程
            int threadCount = (int) (inChannel.size() / (1024 * 8));
            if(inChannel.size() % (1024 * 8) != 0){
                threadCount++;
            }

            //输出线程个数
            System.out.println("线程总数:" + threadCount);
            //创建一个缓存区数组用于存每个线程结束后返回的缓存区
            ByteBuffer[] buffers = new ByteBuffer[threadCount];
            //建立一个线程池
            ExecutorService pool = newFixedThreadPool(threadCount);

            for (int i = 0; i < threadCount; i++) {
                //position是表示每个线程从position的位置开始读取文件进入缓存区
                Future<ByteBuffer> future = pool.submit(new MyTask(inChannel, i * 1024 * 8));

                //线程结束后返回一个ByteBuffer,将他按顺序存入缓存区数组中
                buffers[i] = future.get();
            }

            //两种写入文件的方式
            for (ByteBuffer buffer : buffers) {
                buffer.flip();
                outChannel.write(buffer);
            }
            //outChannel.write(buffers);

            pool.shutdown();
        }finally {
            inChannel.close();
            outChannel.close();
        }
    }

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值