当前位置 博文首页 > qq262593421的博客:java读取文件获取文件名多线程移动文件

    qq262593421的博客:java读取文件获取文件名多线程移动文件

    作者:[db:作者] 时间:2021-08-29 22:24

    一、需求说明

    一个目录里边有 47W个文件,现在需要根据一个文本文件里边的文件名称

    在47W个文件中取出24W个有效文件(根据文本文件里边的文件名取)

    二、设计思路

    1、使用 BufferedReader?逐行读取文本文件,并存入LinkList

    2、使用定长线程池并行处理移动文件

    三、实现代码

    package com.xtd.file.gash.general;
    
    import java.io.*;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    
    public class ReadCSVMove {
    
        private static FileReader fileReader = null;
        private static BufferedReader bufferedReader = null;
        private static List<String> list = new LinkedList<String>();    //247576
        private static final String filePath = "C:\\Users\\com\\Desktop\\测试数据\\EEMMSI.csv";
        private static final String basePath = "E:\\HistoryData\\ArcticOceanData\\ArcticOceanData\\finish\\201707\\";
        private static final String movePath = "C:\\Users\\com\\Desktop\\测试数据\\其他\\";
        private static final ExecutorService fixedThreadPool = Executors.newFixedThreadPool(60);
    
        public static void main(String[] args) {
            readCSV(filePath);
            System.out.println(list.size());
            forDir(basePath,movePath);
        }
    
        /**
         * 遍历文件目录
         * @param basePath
         * @param movePath
         */
        private static void forDir(String basePath,String movePath){
            for(int i=1;i<list.size();i++){
                int finalI = i;
                // 每个线程处理一个 MMSI
                fixedThreadPool.execute(() -> {
                    String sourcePath = basePath + list.get(finalI) + ".csv";
                    String targePath = movePath + list.get(finalI) + ".csv";
                    System.out.println("sourcePath\t" + sourcePath);
                    System.out.println("targePath\t" + targePath);
                    new File(sourcePath).renameTo(new File(targePath));
                });
            }
            // 执行完毕,关闭线程池
            fixedThreadPool.shutdown();
        }
    
        /**
         * 读取CSV文件,存入list
         * @param path
         */
        private static void readCSV(String path){
            try {
                fileReader = new FileReader(path);
                bufferedReader = new BufferedReader(fileReader);
                String str;
                while ( null != (str = bufferedReader.readLine()) ) {
                    list.add(str);
                }
                bufferedReader.close();
                fileReader.close();
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    ?

    ?

    cs