本文執行個體為大家分享了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 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 getFilelist() {
return filelist;
}
public void setFilelist(List 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 fList=new ArrayList();
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();
}
以上就是本文的全部内容,希望對大家的學習有所幫助,也希望大家多多支援腳本之家。