java讀取文件獲取文件名多線程移動文件

一、需求說明

一個目錄裏邊有 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();
        }
    }
}

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章