文件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);
}

}

测试了一下,还不错:[img]http://dl.iteye.com/upload/attachment/588367/57bdf8ac-78ae-3f98-bdb7-efc2f8f2a6d6.png[/img]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值