使用线程完成两个文件中读,再写到一个文件中去

  1. 需求:
    创建线程的两种方式:
      继承Thread类
      实现Runnble接口
    两者的区别在于:
  1. 从功能上,二者皆可
  2. 从简易方法上,继承简单
  3. 考虑到以后模块增加建议使用实现Runnable接口,因为再java中类是单继承,接口可以多继承。
  1. 设计:
    本文采用实现Runnable接口的方法完成。
     
    创建工具类FileUtil
      ①读文件的方法:
/**
 * 读文件
 * @param srcname
 * @return String
 * */
public String  readFile(File srcname){
    synchronized (this){

        StringBuffer sb = new StringBuffer();
        try {
            br =  new BufferedReader(new InputStreamReader(new FileInputStream(srcname),"GBK"));
            String line = "";
            while (null != (line= br.readLine())){
                sb.append(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return  sb.toString();
    }


}

②写文件的方法 

 

**
 * 写文件
 * @param srcname
 * @param  destname
 * */
public void   writeFile(File srcname,File destname){
        try {

            writer=  new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destname,true),"GBK"));
            writer.write(readFile(srcname));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

}

 ③然后我们创建线程类

 

/**
 * 线程类
 * 实现runnable类
 * */
public class FileThread  implements  Runnable{
    FileUtil  fu = new FileUtil();
    private File  src;
    private File  dest;
    public FileThread(File src, File dest){
         this.src = src;
         this.dest = dest;
    }
    @Override
    public void run() {
        fu.writeFile(src,dest);
    }

}

④测试类

 

public static  void  main(String[] args) throws InterruptedException {
    //要读取的文件路径(要存在)
    File src1 = new File("E://The Old Man and the Sea .txt");
    File src2 = new File("E://The Old Man and the Sea1.txt");
    //写的文件路径(可以没有,若没有系统会自动创建)
    File dest1 = new File("E://Hello.txt");
    File dest2 = new File("E://welcome.txt");

    FileThread  t1 = new FileThread(src1,dest1);
    FileThread  t2 = new FileThread(src2,dest2);
    Thread thread1 = new Thread(t1,"Thread1");
    Thread thread2 = new Thread(t2,"Thread2");

    thread1.start();
    thread1.join();
    thread2.start();

}

 

上面程序运行,会正确将两个文件的内容合并写到第三个当中

需要注意的几点有:

  1. 读写的编码要一致,因为只有OutputStreamWriter/InputStreamReader转换流有编码方式,所以我们用该流进行读取
  2. 我们要实现将文件合并写入需要加入追加属性,否则会出现后者覆盖不能达到预期效果,默认为false我们设置为true
  writer=  new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destname,true),"GBK"));

 3.  最最重要的一点
     writer.flush();
如果不写这一行,你可能会发现写文件为空,它的目的为刷新流
 
 
本文中用到了线程的join方法
    线程的join方法表示一个线程等待另一个线程完成后才执行,称之为联合线程,将当前线程和当前线程所在的线程联合成一个线程。A线程需要拿到B的执行结果,才能继续往下。

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值