文件进行归并排序,并将排序好的内容输入按照原始文件的格式到新的文件

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

/**
 * @program:
 * @description: 文件解压缩工具类
 **/
public class FileUtils {

    /**
     * 读取某个文件夹下的所有文件(支持多级文件夹)
     */
    public static void reaSortAndOutPutFile(String filepath, String destFilePath)
            throws FileNotFoundException, IOException {
        File file = new File(filepath);
        if (!file.isDirectory()) {
            int[] arr = readFileByLines(file);
            writeFile(arr, destFilePath, file.getName());
        } else if (file.isDirectory()) {
            String[] filelist = file.list();
            for (int i = 0; i < filelist.length; i++) {
                File readfile = new File(filepath + File.separator + filelist[i]);
                if (!readfile.isDirectory()) {
                    int[] arr = readFileByLines(readfile);
                    writeFile(arr, destFilePath, readfile.getName());
                } else if (readfile.isDirectory()) {
                    reaSortAndOutPutFile(filepath + File.separator + filelist[i], destFilePath);
                }
            }

        }
    }

    public static void writeFile(int[] arr, String destFilePath, String fileName) {
        File file = new File(destFilePath);
        if (!file.exists()) {
            file.mkdir();
        }
        int maxTimes = RadixSort.getMaxTime(arr);
        RadixSort.radixSort(arr, maxTimes);
        FileWriter fileWriter = null;
        try {
            //创建文本文件
            fileWriter = new FileWriter(destFilePath.concat(fileName));
            for (int i = 0; i < arr.length; i++) {
                fileWriter.write(arr[i] + System.getProperty("line.separator"));
            }
            fileWriter.flush();
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 以行为单位读取文件,常用于读面向行的格式化文件
     *
     * @param file 文件名
     */
    public static int[] readFileByLines(File file) throws IOException {
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            int num = Integer.parseInt(reader.readLine());
            int[] arr = new int[num];

            String tempString = null;
            int j = 0;
            // 一次读入一行,直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                arr[j] = Integer.parseInt(tempString);
                j++;
            }
            reader.close();
            return arr;
        } catch (IOException e) {
            throw e;
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    /**
     * @param zip         zip文件位置
     * @param outputDir   解压缩后文件保存路径
     * @param charsetName 字符编码
     */
    public static void unpack(String zip, String outputDir, String charsetName) {
        unpack(new File(zip), new File(outputDir), charsetName);
    }

    /**
     * @param zip         zip文件位置
     * @param outputDir   解压缩后文件保存路径
     * @param charsetName 字符编码
     */
    public static void unpack(File zip, File outputDir, String charsetName) {

        FileOutputStream out = null;
        InputStream in = null;
        //读出文件数据
        ZipFile zipFileData = null;
        ZipFile zipFile = null;
        try {
            //若目标保存文件位置不存在
            if (outputDir != null && !outputDir.exists()) {
                outputDir.mkdirs();
            }
            if (charsetName != null && charsetName != "") {
                zipFile = new ZipFile(zip.getPath(), Charset.forName(charsetName));
            } else {
                zipFile = new ZipFile(zip.getPath(), Charset.forName("utf8"));
            }
            //zipFile = new ZipFile(zip.getPath(), Charset.forName(charsetName));
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            //处理创建文件夹
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                String filePath = "";

                if (outputDir == null) {
                    filePath = zip.getParentFile().getPath() + File.separator + entry.getName();
                } else {
                    filePath = outputDir.getPath() + File.separator + entry.getName();
                }
                File file = new File(filePath);
                File parentFile = file.getParentFile();
                if (!parentFile.exists()) {
                    parentFile.mkdirs();
                }
                if (parentFile.isDirectory()) {
                    continue;
                }
            }
            if (charsetName != null && charsetName != "") {
                zipFileData = new ZipFile(zip.getPath(), Charset.forName(charsetName));
            } else {
                zipFileData = new ZipFile(zip.getPath(), Charset.forName("utf8"));
            }
            Enumeration<? extends ZipEntry> entriesData = zipFileData.entries();
            while (entriesData.hasMoreElements()) {
                ZipEntry entry = entriesData.nextElement();
                in = zipFile.getInputStream(entry);
                String filePath = "";
                if (outputDir == null) {
                    filePath = zip.getParentFile().getPath() + File.separator + entry.getName();
                } else {
                    filePath = outputDir.getPath() + File.separator + entry.getName();
                }
                File file = new File(filePath);
                if (file.isDirectory()) {
                    continue;
                }
                out = new FileOutputStream(filePath);
                int len = -1;
                byte[] bytes = new byte[1024];
                while ((len = in.read(bytes)) != -1) {
                    out.write(bytes, 0, len);
                }
                out.flush();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                in.close();
                zipFile.close();
                zipFileData.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static List<String> getFileFullName(String sourceFilePath) throws IOException {
        List<String> fileNames = new ArrayList<>();
        File f = new File(sourceFilePath);
        File[] files = f.listFiles();
        for (File temp : files) {
            fileNames.add(temp.getCanonicalPath());
        }
        return fileNames;
    }

}

import java.util.List;

public class Main {

    public static void main(String[] args) throws Exception {
        String zipDir = "/Users/liujiaqiang/Desktop/test.zip";
        String outputDir = "/Users/liujiaqiang/Desktop/zip";
        String sortDir = "/Users/liujiaqiang/Desktop/sortDir/";
        //解压zip文件
        FileUtils.unpack(zipDir, outputDir, "utf-8");
        FileUtils.reaSortAndOutPutFile(outputDir, sortDir);
        List<String> fileNames = FileUtils.getFileFullName(sortDir);
        MergeSort sorter = new MergeSort(fileNames, "output.txt");
        sorter.sort();
        sorter.close();

    }
}

/**
 * Created by liujiaqiang on 2020/6/21.
 */

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 对文件进行排序合并
 */
public class MergeSort implements Closeable {

    private List<MergeSource> sources;

    private MergeOut out;

    public MergeSort(List<String> files, String outFilename) {
        this.sources = new ArrayList<>();
        for (String filename : files) {
            this.sources.add(new MergeSource(filename));
        }
        this.out = new MergeOut(outFilename);
    }

    static class MergeOut implements Closeable {

        private PrintWriter writer;

        public MergeOut(String filename) {
            try {
                this.writer = new PrintWriter(new FileOutputStream(filename));
            } catch (FileNotFoundException e) {
            }
        }

        public void write(Bin bin) {
            writer.println(String.format("%04d", bin.num));
        }

        @Override
        public void close() throws IOException {
            writer.flush();
            writer.close();
        }
    }

    static class MergeSource implements Closeable {

        private BufferedReader reader;

        private String cachedLine;

        public MergeSource(String filename) {
            try {
                FileReader fr = new FileReader(filename);
                this.reader = new BufferedReader(fr);
            } catch (FileNotFoundException e) {
            }
        }

        public boolean hasNext() {
            String line;
            try {
                line = this.reader.readLine();
                if (line == null || line.isEmpty()) {
                    return false;
                }
                this.cachedLine = line.trim();
                return true;
            } catch (IOException e) {
            }
            return false;
        }

        public int next() {
            if (this.cachedLine == null) {
                if (!hasNext()) {
                    throw new IllegalStateException("no content");
                }
            }
            int num = Integer.parseInt(this.cachedLine);
            this.cachedLine = null;
            return num;
        }

        @Override
        public void close() throws IOException {
            this.reader.close();
        }
    }

    static class Bin implements Comparable<Bin> {

        int num;

        MergeSource source;

        Bin(MergeSource source, int num) {
            this.source = source;
            this.num = num;
        }

        @Override
        public int compareTo(Bin o) {
            return o.num - this.num;
        }
    }

    public List<Bin> prepare() {
        List<Bin> bins = new ArrayList<>();
        for (MergeSource source : sources) {
            Bin newBin = new Bin(source, source.next());
            bins.add(newBin);
        }
        Collections.sort(bins);
        return bins;
    }

    public void sort() {
        List<Bin> bins = prepare();
        while (true) {
            MergeSource current = bins.get(0).source;
            if (current.hasNext()) {
                Bin newBin = new Bin(current, current.next());
                int index = Collections.binarySearch(bins, newBin);
                if (index == 0 || index == -1) {
                    this.out.write(newBin);
                    if (index == -1) {
                        throw new IllegalStateException("impossible");
                    }
                } else {
                    if (index < 0) {
                        index = -index - 1;
                    }
                    bins.add(index, newBin);
                    Bin minBin = bins.remove(0);
                    this.out.write(minBin);
                }
            } else {
                Bin minBin = bins.remove(0);
                this.out.write(minBin);
                if (bins.isEmpty()) {
                    break;
                }
            }
        }
    }

    @Override
    public void close() throws IOException {
        for (MergeSource source : sources) {
            source.close();
        }
        this.out.close();
    }

}



import java.util.LinkedList;
import java.util.Queue;

/**
 *
 */
public class RadixSort {

    /**
     * @param array    数组arr
     * @param maxTimes 数组的最大位数
     */
    public static void radixSort( int[] array, int maxTimes) {
        int i, j, k;
        Queue<Integer>[] que = new Queue[10];
        for (i = 0; i < 10; i++) {
            que[i] = new LinkedList<Integer>();
        }

        int length = array.length;
        for (i = 0; i < maxTimes; i++) {
            for (j = 0; j < length; j++) {
                k = digit(array[j], i);
                que[k].add(array[j]);
            }
            j = 0;
            for (k = 9; k > -1; k--) {
                while (!que[k].isEmpty()) {
                    array[j++] = que[k].remove();
                }
            }

        }

    }

    /**
     * 获取最大值;要看排几次,主要看这个最大值有几位;
     *
     * @param array
     * @return
     */
    public static int getMaxTime( int[]  array) {
        int max = 0;
        for (int i = 0; i < array.length; i++) {
            if (max < array[i]) {
                max = array[i];
            }
        }
        //获取最大值位数;
        //求取这个最大值的位数,依次除以10;直到为0;
        int times = 0;
        while (max > 0) {
            max /= 10;
            times++;
        }
        return times;
    }

    /**
     * @param data
     * @param m
     * @return
     */
    public static int digit(int data, int m) {
        int i, d;
        if (m == 0) {
            return data % 10;
        }
        d = 10;
        for (i = 1; i < m; i++) {
            d = d * 10;
        }
        return (data / d) % 10;
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值