- 需求:
创建线程的两种方式:
继承Thread类
实现Runnble接口
两者的区别在于:
- 从功能上,二者皆可
- 从简易方法上,继承简单
- 考虑到以后模块增加建议使用实现Runnable接口,因为再java中类是单继承,接口可以多继承。
- 设计:
本文采用实现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();
}
上面程序运行,会正确将两个文件的内容合并写到第三个当中
需要注意的几点有:
- 读写的编码要一致,因为只有OutputStreamWriter/InputStreamReader转换流有编码方式,所以我们用该流进行读取
- 我们要实现将文件合并写入需要加入追加属性,否则会出现后者覆盖不能达到预期效果,默认为false我们设置为true
writer= new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destname,true),"GBK"));
3. 最最重要的一点
writer.flush();
如果不写这一行,你可能会发现写文件为空,它的目的为刷新流
本文中用到了线程的join方法
线程的join方法表示一个线程等待另一个线程完成后才执行,称之为联合线程,将当前线程和当前线程所在的线程联合成一个线程。A线程需要拿到B的执行结果,才能继续往下。