排序-JAVA实现【十一】大文件排序

问题说明:有一个无续long型的大文件,超过系统内存,需要对其进行排序。

大文件排序,多线程并发处理:


import lombok.SneakyThrows;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 大文件排序
 */
public class BigFileSort {
    private static final Random RANDOM = new Random();

    private long splitLength = 10;

    private AtomicInteger atomicInteger = new AtomicInteger();

    private int totalThread = 0;

    public BigFileSort(long splitLength) {
        this.splitLength = splitLength;
    }

    /**
     * 创建大文件
     */
    public void createBigFile(String fileName, long amount) throws IOException {

        FileOutputStream out = null;

        try {
            File file = new File(fileName);
            if (file.exists()) {
                if (file.isDirectory()) {
                    throw new IOException("File '" + file + "' exists but is a directory");
                }

                if (!file.canWrite()) {
                    throw new IOException("File '" + file + "' cannot be written to");
                }
            } else {
                File parent = file.getParentFile();
                if (parent != null && !parent.exists() && !parent.mkdirs()) {
                    throw new IOException("File '" + file + "' could not be created");
                }
            }

            out = new FileOutputStream(file);

            for (long i = 0; i < amount; i ++) {
                long value = RANDOM.nextLong();
                value = value < 0 ? -value : value;
                out.write(String.valueOf(value + " ").getBytes());
            }

        } finally {
            IOUtils.closeQuietly(out);
        }

    }

    /**
     * 拆分小文件
     */
    public void splitFile(String fileName) throws IOException {
        FileInputStream fis = null;
        FileOutputStream out = null;
        try {
            File file = new File(fileName);
            fis = new FileInputStream(file);

            int temp = 0;
            //当temp等于-1时,表示已经到了文件结尾,停止读取
            String fileParent = file.getParentFile().getAbsolutePa
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值