JAVA多线程读写文件范例

   在写之前先声明,本文是基于之前在博客园网站上检索到的一份JAVA多线程读写文件的示例,我在写自己的程序时是在那位作者写的基础上做了改良,但已不记得原文的地址。如果有知情者,烦请帖出地址,我在此文上加入引用或转载。 


    本程序是基于这么一种考虑,某系统后台有个将近2G大小的日志文件,你用任何编辑器去打开它,都将会很困难。针对这样的大文件解析处理,解决方案是使用多个线程,分割读取指定的大文件。获取我们所需要的信息。不多说,上代码了,有注释可以帮助理解。 


   

Java代码  收藏代码
  1. package com.thread.multipl.mysolution;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.RandomAccessFile;  
  5. import java.util.concurrent.CountDownLatch;  
  6.   
  7. /** 
  8.  * 这个线程用来读取文件,当获取到指定关键字时,在指定的对象加1 
  9.  * @author 刘峰管理2 
  10.  * 
  11.  */  
  12. public class ReadThread extends Thread{  
  13.   
  14.     //定义字节数组(取水的竹筒)的长度    
  15.     private final int BUFF_LEN = 256;    
  16.     //定义读取的起始点    
  17.     private long start;    
  18.     //定义读取的结束点    
  19.     private long end;   
  20.     //将读取到的字节输出到raf中  randomAccessFile可以理解为文件流,即文件中提取指定的一部分的包装对象  
  21.     private RandomAccessFile raf;    
  22.     //线程中需要指定的关键字  
  23.     private String keywords;  
  24.     //此线程读到关键字的次数  
  25.     private int curCount = 0;  
  26.     /** 
  27.      * jdk1.5开始加入的类,是个多线程辅助类 
  28.      * 用于多线程开始前统一执行操作或者多线程执行完成后调用主线程执行相应操作的类 
  29.      */  
  30.     private CountDownLatch doneSignal;  
  31.     public ReadThread(long start, long end, RandomAccessFile raf,String keywords,CountDownLatch doneSignal){  
  32.         this.start = start;  
  33.         this.end = end;  
  34.         this.raf  = raf;  
  35.         this.keywords = keywords;  
  36.         this.doneSignal = doneSignal;  
  37.     }  
  38.       
  39.     public void run(){  
  40.         try {  
  41.             raf.seek(start);  
  42.             //本线程负责读取文件的大小    
  43.             long contentLen = end - start;    
  44.             //定义最多需要读取几次就可以完成本线程的读取    
  45.             long times = contentLen / BUFF_LEN+1;    
  46.             System.out.println(this.toString() + " 需要读的次数:"+times);  
  47.             byte[] buff = new byte[BUFF_LEN];  
  48.             int hasRead = 0;  
  49.             String result = null;  
  50.             for (int i = 0; i < times; i++) {    
  51.                 //之前SEEK指定了起始位置,这里读入指定字节组长度的内容,read方法返回的是下一个开始读的position  
  52.                 hasRead = raf.read(buff);  
  53.                  //如果读取的字节数小于0,则退出循环! (到了字节数组的末尾)   
  54.                 if (hasRead < 0) {    
  55.                     break;    
  56.                 }    
  57.                 result = new String(buff,"gb2312");  
  58. ///             System.out.println(result);  
  59.                 int count = this.getCountByKeywords(result, keywords);  
  60.                 if(count > 0){  
  61.                     this.curCount += count;  
  62.                 }  
  63.             }  
  64.               
  65.             KeyWordsCount kc = KeyWordsCount.getCountObject();  
  66.   
  67.             kc.addCount(this.curCount);  
  68.               
  69.             doneSignal.countDown();//current thread finished! noted by latch object!  
  70.         } catch (IOException e) {  
  71.             // TODO Auto-generated catch block  
  72.             e.printStackTrace();  
  73.         }  
  74.     }  
  75.   
  76.     public long getStart() {  
  77.         return start;  
  78.     }  
  79.   
  80.     public void setStart(long start) {  
  81.         this.start = start;  
  82.     }  
  83.   
  84.     public long getEnd() {  
  85.         return end;  
  86.     }  
  87.   
  88.     public void setEnd(long end) {  
  89.         this.end = end;  
  90.     }  
  91.   
  92.     public RandomAccessFile getRaf() {  
  93.         return raf;  
  94.     }  
  95.   
  96.     public void setRaf(RandomAccessFile raf) {  
  97.         this.raf = raf;  
  98.     }  
  99.       
  100.     public int getCountByKeywords(String statement,String key){  
  101.         return statement.split(key).length-1;  
  102.     }  
  103.   
  104.     public int getCurCount() {  
  105.         return curCount;  
  106.     }  
  107.   
  108.     public void setCurCount(int curCount) {  
  109.         this.curCount = curCount;  
  110.     }  
  111.   
  112.     public CountDownLatch getDoneSignal() {  
  113.         return doneSignal;  
  114.     }  
  115.   
  116.     public void setDoneSignal(CountDownLatch doneSignal) {  
  117.         this.doneSignal = doneSignal;  
  118.     }  
  119. }  



Java代码  收藏代码
  1. package com.thread.multipl.mysolution;  
  2.   
  3. import java.io.File;  
  4. import java.io.RandomAccessFile;  
  5. import java.util.concurrent.CountDownLatch;  
  6.   
  7. public class MultiReadTest {  
  8.   
  9.     /** 
  10.      * 多线程读取文件测试 
  11.      * @param args 
  12.      */  
  13.     public static void main(String[] args) {  
  14.         // TODO Auto-generated method stub  
  15.         final int DOWN_THREAD_NUM = 10;//起10个线程去读取指定文件  
  16.         final String OUT_FILE_NAME = "d:\\倚天屠龙记.txt";  
  17.         final String keywords = "无忌";  
  18.          //jdk1.5线程辅助类,让主线程等待所有子线程执行完毕后使用的类,  
  19.         //另外一个解决方案:自己写定时器,个人建议用这个类  
  20.         CountDownLatch doneSignal = new CountDownLatch(DOWN_THREAD_NUM);  
  21.         RandomAccessFile[] outArr = new RandomAccessFile[DOWN_THREAD_NUM];  
  22.         try{  
  23.             long length = new File(OUT_FILE_NAME).length();  
  24.             System.out.println("文件总长度:"+length+"字节");  
  25.             //每线程应该读取的字节数    
  26.             long numPerThred = length / DOWN_THREAD_NUM;    
  27.             System.out.println("每个线程读取的字节数:"+numPerThred+"字节");  
  28.           //整个文件整除后剩下的余数    
  29.             long left = length % DOWN_THREAD_NUM;  
  30.             for (int i = 0; i < DOWN_THREAD_NUM; i++) {    
  31.                 //为每个线程打开一个输入流、一个RandomAccessFile对象,    
  32.                   
  33.                 //让每个线程分别负责读取文件的不同部分  
  34.                 outArr[i] = new RandomAccessFile(OUT_FILE_NAME, "rw");    
  35.                 if (i != 0) {    
  36. //    
  37. //                    isArr[i] = new FileInputStream("d:/勇敢的心.rmvb");    
  38.                     //以指定输出文件创建多个RandomAccessFile对象    
  39.                       
  40.                 }    
  41.                 if (i == DOWN_THREAD_NUM - 1) {    
  42. //                    //最后一个线程读取指定numPerThred+left个字节    
  43. //                  System.out.println("第"+i+"个线程读取从"+i * numPerThred+"到"+((i + 1) * numPerThred+ left)+"的位置");  
  44.                     new ReadThread(i * numPerThred, (i + 1) * numPerThred    
  45.                             + left, outArr[i],keywords,doneSignal).start();    
  46.                 } else {    
  47.                     //每个线程负责读取一定的numPerThred个字节    
  48. //                  System.out.println("第"+i+"个线程读取从"+i * numPerThred+"到"+((i + 1) * numPerThred)+"的位置");  
  49.                     new ReadThread(i * numPerThred, (i + 1) * numPerThred,    
  50.                             outArr[i],keywords,doneSignal).start();    
  51.                 }    
  52.             }  
  53.         }catch(Exception e){  
  54.             e.printStackTrace();  
  55.         }  
  56. //      finally{  
  57. //            
  58. //      }  
  59.         //确认所有线程任务完成,开始执行主线程的操作  
  60.         try {  
  61.             doneSignal.await();  
  62.         } catch (InterruptedException e) {  
  63.             // TODO Auto-generated catch block  
  64.             e.printStackTrace();  
  65.         }  
  66.         //这里需要做个判断,所有做read工作线程全部执行完。  
  67.         KeyWordsCount k = KeyWordsCount.getCountObject();  
  68. //      Map<String,Integer> resultMap = k.getMap();  
  69.         System.out.println("指定关键字出现的次数:"+k.getCount());  
  70.     }  
  71.   
  72. }  



Java代码  收藏代码
  1. package com.thread.multipl.mysolution;  
  2.   
  3.   
  4. /** 
  5.  * 统计关键字的对象 
  6.  * @author 刘峰管理2 
  7.  * 
  8.  */  
  9.   
  10. public class KeyWordsCount {  
  11.       
  12.     private static KeyWordsCount kc;  
  13.       
  14.     private int count = 0;  
  15.     private KeyWordsCount(){  
  16.           
  17.     }  
  18.       
  19.     public static synchronized KeyWordsCount getCountObject(){  
  20.         if(kc == null){  
  21.             kc = new KeyWordsCount();  
  22.         }  
  23.         return kc;  
  24.     }  
  25.   
  26.     public synchronized void  addCount(int count){  
  27.         System.out.println("增加次数:"+count);  
  28.         this.count += count;  
  29.     }  
  30.       
  31.     public int getCount() {  
  32.         return count;  
  33.     }  
  34.   
  35.     public void setCount(int count) {  
  36.         this.count = count;  
  37.     }  
  38.       
  39. }  



运行结果如下: 

引用
文件总长度:2012606字节 
每个线程读取的字节数:201260字节 
Thread[Thread-0,5,main] 需要读的次数:787 
Thread[Thread-1,5,main] 需要读的次数:787 
Thread[Thread-2,5,main] 需要读的次数:787 
Thread[Thread-3,5,main] 需要读的次数:787 
Thread[Thread-4,5,main] 需要读的次数:787 
Thread[Thread-5,5,main] 需要读的次数:787 
Thread[Thread-6,5,main] 需要读的次数:787 
Thread[Thread-7,5,main] 需要读的次数:787 
Thread[Thread-8,5,main] 需要读的次数:787 
Thread[Thread-9,5,main] 需要读的次数:787 
增加次数:0 
增加次数:146 
增加次数:432 
增加次数:539 
增加次数:587 
增加次数:717 
增加次数:631 
增加次数:467 
增加次数:665 
增加次数:538 
指定关键字出现的次数:4722



我用10个线程去解析金庸大师写的《倚天屠龙记》,“无忌”这个词在这部小说中一共出现了4722次。实在找不到再大一些的文件了。倚天屠龙记.txt的大小4M出头。 

关于CountDownLatch类的作用说明: 
    在API文档中,已经说明是一个辅助类。用于控制主线程与子线程之间切换的一个工具类。用法网上去搜下。ITEYE里也有人讨论过。我在这里使用它解决这样的问题:在确保10个线程都完成文件的解析工作后,系统调用主线程做剩下该做的事情,即:输出“出现的次数”。不确保这点的话,会导致执行完第4个线程,后面的线程还没开始,系统已经做最后一步输出统计结果,这样就达不到我们要的效果。这里解决方案有另一个简单的,自己写个计数器,从10记到1,10个线程嘛。这个看个人喜好吧。

原文:http://babystudyjava.iteye.com/blog/1732814

posted @ 2014-07-28 21:12  jack_ou  阅读(43807)  评论(5编辑  收藏  举报