ITeye博客

文件io测试

andyjackson · 2011-11-15 01:02 · java · 企业架构 · Markdown

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

/**
 * @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);
	}

}

测试了一下,还不错:

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。