java 多线程读取多个文件

package com.linkage.bss.agent.service.common;

import java.io.*;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * 多线程读取多个文件
 */
public class FileThread extends Thread{

    private final CountDownLatch countDownLatch = new CountDownLatch(10);
    private int fileIndex;
    private List<String> filelist;
    private String filepath = "D:\\LocalFtpServer\\data20181229\\";
    private String movepath = "D:\\LocalFtpServer\\data20181229_01\\";

    public int getFileIndex() {
        return fileIndex;
    }

    public void setFileIndex(int fileIndex) {
        this.fileIndex = fileIndex;
    }

    public List<String> getFilelist() {
        return filelist;
    }

    public void setFilelist(List<String> filelist) {
        this.filelist = filelist;
    }

    @Override
    public void run() {

        for (int i = 0; i < filelist.size(); i++) {
            if (i % 10 == fileIndex) {
                //读取文件
                File readfile = new File(filepath + filelist.get(i));
                InputStreamReader isr = null;
                try {
                    isr = new InputStreamReader(new FileInputStream(readfile), "UTF-8");
                    BufferedReader reader = new BufferedReader(isr);
                    String line = null;
                    // 一次读入一行,直到读入null为文件结束
                    while ((line = reader.readLine()) != null) {
                        System.out.println(line );
                    }
                    reader.close();
                    isr.close();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //读取完后, 移动文件位置
                readfile.renameTo(new File(movepath + readfile.getName()));
            }
        }
        countDownLatch.countDown();
    }
}

猜你喜欢

转载自blog.csdn.net/HoneyYHQ9988/article/details/85601628