本文实例为大家分享了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(); }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持呐喊教程。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。