首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

资料io测试

2012-06-27 
文件io测试简而言之,就是利用回调模式,在线程完成了操作之后调用主线程了监听方法。废话不说,上码:监听接口

文件io测试
简而言之,就是利用回调模式,在线程完成了操作之后调用主线程了监听方法。废话不说,上码:
监听接口,继承该类实现回调

/** * @author ajwang * 回调接口  * */public interface DigestListener {public void digestCalculated(List<String> list) throws IOException; }

具体的线程类,读取文件
/** * @author ajwang * */public class ListCallbackDigest implements Runnable {private File inputFile;     private DigestListener digestListener;    public ListCallbackDigest(File inputFile, DigestListener digestListener) {         this.inputFile = inputFile;         this.digestListener=digestListener;    }     public void run() {         try {             BufferedReader br = new BufferedReader(new FileReader(inputFile));            List<String> result = new ArrayList<String>();            String temp="";            while((temp=br.readLine() )!= null){            result.add(temp);            }            //进行回调            digestListener.digestCalculated(result);        } catch (FileNotFoundException e) {             e.printStackTrace();         } catch (IOException e) {e.printStackTrace();}    } }

继承监听接口,实现线程监听回调
/** * @author ajwang *  */public class ListCallbackDigestUser implements DigestListener {private BufferedWriter bw;private int counter;private int current=0;private long start;public ListCallbackDigestUser(String outFIlePath) throws IOException {this.bw = new BufferedWriter(new FileWriter(new File(outFIlePath)));}public synchronized void digestCalculated(List<String> list)throws IOException {for (String s : list) {//System.out.println(s);bw.write(s);bw.newLine();}this.current++;if(current>=counter){bw.flush();bw.close();long end =System.nanoTime();System.out.println("系统用时:"+(end-start));}}public void process(String[] arr) {start =System.nanoTime();this.counter=arr.length;for (int i = 0; i < arr.length; i++) {File f = new File(arr[i]);new Thread(new ListCallbackDigest(f, this)).start();}}public static void main(String[] args) throws IOException {ListCallbackDigestUser me = new ListCallbackDigestUser("/home/8888/Desktop/test/out.txt");String arr[] = { "/home/ajwang/Desktop/test/xcopy.txt","/home/***8/Desktop/test/x.txt","/home/***8/Desktop/test/xb.txt","/home/****/Desktop/test/bf2.txt","/home/****/Desktop/test/bf2.txt" };me.process(arr);}}

测试了一下,还不错:

热点排行