首先定义一类,实现Thread接口的方法,找一个自己想要拷贝的目录和目标目录,利用Io流读写文件,完成拷贝
public class copyFile extends Thread {
//需要拷贝的文件
private File files = new File("/Users/apple/Documents/mp3/测试/javaio.txt");
//需要拷贝到的地址
private File filous = new File("/Users/apple/Documents/mp3/未命名文件夹/ceshi.txt");
@Override
public void run() {
try {
//串联字符流 读写文件
FileInputStream is = new FileInputStream(files);
FileOutputStream os = new FileOutputStream(filous);
int len = 0;
double s = files.length();
//声明一个零时变量,用于计算读写进度
double cd = 0.0;
byte[] buff = new byte[8];
while ((len = is.read(buff)) != -1) {
cd = cd + len;
//利用NumberFormat转换为百分比格式
NumberFormat num = NumberFormat.getPercentInstance();
String rates = num.format(cd / s);
os.write(buff, 0, len);
System.out.println(rates);
try {
//由于文件过小,拷贝瞬间完成,我设置休眠间隔1s,所有异常直接捕获.
sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.run();
}
public static void main(String[] args) {
copyFile t = new copyFile();
t.start();
}