复制文件的实现:(带显示进度)
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
public class Test {
//全局变量,用以计算进度
static Double totalLength = 0.0;
static Double currentLength = 0.0;
//主函数
public static void main(String[] args) throws IOException {
//线程调用复制文件的方法
Thread thread1 = new Thread(new Runnable() {
//源文件地址(修改为需要复制的文件路径)
String sourceFile = "E://windows_7_sp1_x64.iso";
//目标地址(修改为复制到的路径)
String destionalFile = "E://test1.iso";
//线程名称
String name = "thread1";
@Override
public void run() {
try {
copy(sourceFile, destionalFile, name);
} catch (IOException e) {
e.printStackTrace();
}
}
});
Thread thread2 = new Thread(new Runnable() {
String sourceFile = "E://VS2015.iso";
String destionalFile = "E://test2.iso";
String name = "thread2";
@Override
public void run() {
try {
copy(sourceFile, destionalFile, name);
} catch (IOException e) {
e.printStackTrace();
}
}
});
thread1.start();
// thread2.start();
timerTask();
}
/**
*
* @param sourceFile 源文件地址
* @param destinationFile 目标文件地址
* @param threadname 当前的线程名称
* @throws IOException
*/
//复制文件方法
public static void copy(String sourceFile, String destinationFile,
String threadname) throws IOException {
InputStream in = null;
OutputStream out = null;
try {
// 源文件
File soruceFile = new File(sourceFile);
if (!soruceFile.exists()) {
System.out.println("源文件不存在!!");
return;
}
totalLength = (double) soruceFile.length();
in = new BufferedInputStream(new FileInputStream(soruceFile));
// 判断要复制的目的文件是否存在
File destFile = new File(destinationFile);
if (!destFile.exists()) {
destFile.createNewFile();
}
out = new BufferedOutputStream(new FileOutputStream(destFile));
byte[] buffer = new byte[128];
while (in.read(buffer) != -1) {
out.write(buffer);
currentLength += buffer.length;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
in.close();
out.close();
}
}
/**
* 每隔2秒报告进度
*/
public static void timerTask(){
java.util.Timer timer = new java.util.Timer(false);
java.util.TimerTask task = new java.util.TimerTask(){
@Override
public void run() {
System.out.println("当前时间为:"+new Date());
System.out.println("当前的复制进度为:"+((int)((currentLength) / (totalLength) * 100))+"%");
}
};
java.util.Date time = new java.util.Date();
long delay = 2000;
long period = 5000;
//启动定时任务,立即执行壹次退出
// timer.schedule(task, time);
//启动定时任务,在 time 指定的时间执行壹次,然后每隔两秒执行壹次
timer.schedule(task, time, delay);
//启动定时任务,从现在起过两秒执行壹次,然后退出
// timer.schedule(task, delay);
//启动定时任务,从现在起过两秒以后,每隔五秒执行壹次
// timer.schedule(task, delay, period);
}
}