欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java多线程读取多个文件的方法

程序员文章站 2023-10-30 18:33:22
本文实例为大家分享了java多线程读取多个文件的具体代码,供大家参考,具体内容如下 工具类代码如下: import java.io.*; import jav...

本文实例为大家分享了java多线程读取多个文件的具体代码,供大家参考,具体内容如下

工具类代码如下:

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();
 }
}

调用测试:

 public static void main(string[] args) throws ioexception {
 string filepath = "d:\\localftpserver\\data20181229\\";
 file file = new file(filepath);
 //读取目录下所有文件
 string[] filelist = file.list();
 list<string> flist=new arraylist<string>();

 for (int i = 0; i < filelist.length; i++) {
 if (filelist[i].startswith("data") && filelist[i].endswith(".txt")) {
  flist.add(filelist[i]);
 }
 }
 for(int i=0;i<30;i++){
 filethread filethread=new filethread();
 filethread.setfileindex(i);
 filethread.setfilelist(flist);
 filethread.start();
 }
 countdownlatch.await();
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。