多线程读取文件

package demo.demo;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.security.InvalidParameterException;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
 
public class ThreadReadFileHelper {
    // 模拟数据
    private static void writeData() throws FileNotFoundException, IOException {
        FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\lianghaohui\\Desktop\\test.txt");
        Random random = new Random();
        for (int n = 0; n < 1000000; n++) {
            int count = random.nextInt(10) + 1;
            StringBuilder builder = new StringBuilder();
 
            for (int i = 0; i < count; i++) {
                builder.append(UUID.randomUUID().toString());
            }
 
            builder.append("\n");
            fileOutputStream.write(builder.toString().getBytes());
        }
        fileOutputStream.close();
        System.out.println("ok");
    }
 
    private static AtomicInteger atomicInteger = new AtomicInteger(0);


    public static void main(String[] args) throws Exception {
        long beginTime = System.currentTimeMillis();
        ThreadReadFileHelper helper = new ThreadReadFileHelper();
 helper.read("C:\\Users\\lianghaohui\\Desktop\\test.txt",Runtime.getRuntime().availableProcessors(),'\n',new StringCallback("UTF-8") {
            @Override
            void callback(String data) {
                int count = atomicInteger.incrementAndGet();
                System.out.println(count);
                if (count == 1000000) {
                    System.out.println("总耗时毫秒:" + (System.currentTimeMillis() - beginTime));
                    System.out.println(data);
                }
            }
        });
    }
 
    public void read(String path, int threadCount, char separator, StringCallback callback) throws IOException {
 
        if (threadCount < 1) {
            throw new InvalidParameterException("The threadCount can not be less than 1");
        }
 
        if (path == null || path.isEmpty()) {
            throw new InvalidParameterException("The path can not be null or empty");
        }
 
        if (callback == null) {
            throw new InvalidParameterException("The callback can not be null");
        }
 
        RandomAccessFile randomAccessFile = new RandomAccessFile(path, "r");
 
        long fileTotalLength = randomAccessFile.length();
        long gap = fileTotalLength / threadCount;
        long checkIndex = 0;
        long[] beginIndexs = new long[threadCount];
        long[] endIndexs = new long[threadCount];
 
        for (int n = 0; n < threadCount; n++) {
            beginIndexs[n] = checkIndex;
            if (n + 1 == threadCount) {
                endIndexs[n] = fileTotalLength;
                break;
            }
            checkIndex += gap;
            long gapToEof = getGapToEof(checkIndex, randomAccessFile, separator);
 
            checkIndex += gapToEof;
            endIndexs[n] = checkIndex;
        }
 
        ExecutorService executorService = Executors.newFixedThreadPool(threadCount);
        executorService.execute(() -> {
            try {
                readData(beginIndexs[0], endIndexs[0], path, randomAccessFile, separator, callback);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
 
        for (int n = 1; n < threadCount; n++) {
            long begin = beginIndexs[n];
            long end = endIndexs[n];
            executorService.execute(() -> {
                try {
                    readData(begin, end, path, null, separator, callback);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }
    }
 
    private long getGapToEof(long beginIndex, RandomAccessFile randomAccessFile, char separator) throws IOException {
        randomAccessFile.seek(beginIndex);
        long count = 0;
 
        while (randomAccessFile.read() != separator) {
            count++;
        }
 
        count++;
 
        return count;
    }
 
    private void readData(long begin, long end, String path, RandomAccessFile randomAccessFile, char separator, StringCallback callback) throws FileNotFoundException, IOException {
        System.out.println("开始工作" + Thread.currentThread().getName());
        if (randomAccessFile == null) {
            randomAccessFile = new RandomAccessFile(path, "r");
        }
 
        randomAccessFile.seek(begin);
        StringBuilder builder = new StringBuilder();
 
        while (true) {
            int read = randomAccessFile.read();
            begin++;
            if (separator == read) {
                if (callback != null) {
                    callback.callback0(builder.toString());
                }
                builder = new StringBuilder();
            } else {
                builder.append((char) read);
            }
 
            if (begin >= end) {
                break;
            }
        }
        randomAccessFile.close();
    }
 
    public static abstract class StringCallback {
        private String charsetName;
        private ExecutorService executorService = Executors.newSingleThreadExecutor();
 
        public StringCallback(String charsetName) {
            this.charsetName = charsetName;
        }
 
        private void callback0(String data) {
            executorService.execute(() -> {
                try {
                    callback(new String(data.getBytes("ISO-8859-1"), charsetName));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            });
 
        }
 
        abstract void callback(String data);
    }
 
}
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值