用一个线程来控制文件的拷贝,另一个线程来控制拷贝的进度
package com.softeem.thread;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.text.DecimalFormat;
import java.util.RandomAccess;
/**
* 使用一个线程进行文件拷贝,另一个子线程返回当前拷贝的进度 (守护线程)
* @author LuFeng
*
*/
public class ThreadDemo extends Thread{
private File source;
private File dir;
public ThreadDemo(File source, File dir) {
super();
this.source = source;
this.dir = dir;
}
RandomAccessFile ra_in=null;
RandomAccessFile ra_out=null;
@Override
public void run() {
try {
long current=0;
ra_in=new RandomAccessFile(source, "r");
ra_out=new RandomAccessFile(dir, "rw");
byte[] b=new byte[1024];
int len=0;
System.out.println("开始拷贝。。。。");
ThreadDeno td=new ThreadDeno(source.length(), current);
td.start();
while((len=ra_in.read(b))!=-1) {
ra_out.write(b,0,len);
current+=len;
//设置当前的进度
td.setCurrent(current);
}
System.out.println("拷贝完成。。。。");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (ra_in!=null) {
ra_in.close();
}
if (ra_out!=null) {
ra_out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 守护进程的线程
* @author LuFeng
*
*/
class ThreadDeno extends Thread{
private long total;
private long current;
public ThreadDeno(long total, long current) {
super();
this.total = total;
this.current = current;
}
public long getCurrent() {
return current;
}
public void setCurrent(long current) {
this.current = current;
}
@Override
public void run() {
while(current<total) {
double a=(double)current/total;
//将小数格式化成百分数
DecimalFormat df=(DecimalFormat) DecimalFormat.getPercentInstance();
String str=df.format(a);
System.out.println("当前进度:"+str);
}
}
}
public static void main(String[] args) {
File source=new File("F:\\迅雷下载\\hello\\video1.mp4");
File dir=new File("F:\\迅雷下载\\word1\\video.mp4");
ThreadDemo t=new ThreadDemo(source, dir);
t.start();
}
}