Java之面向对象小程序4

 用线程来求文件复制的进度

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Q3 extends Thread {

	static double bytex;//原文件总大小
	static double newbytes;//复制文件大小

	public static void copy2(File source, File dir) {
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			bis = new BufferedInputStream(new FileInputStream(source));
			bos = new BufferedOutputStream(new FileOutputStream(dir));//完成初始化
			bytex = source.length();
            int len = 0;
            byte[] bytes = new byte[1024 * 1024];//定义一个byte型数组,用来充当复制过程的中间数组,储存缓冲数据
			while ((len = bis.read(bytes)) != -1) {//当read方法返回-1 ,表示文件结尾
				bos.write(bytes, 0, len);//从指定的字节数组bytes写入(len-0)个字节
				newbytes = dir.length();
			}
			bos.close();
			bis.close();//关流
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
    
    /**
	 * 用副线程来求文件复制进度
	 */
	@Override
	public void run() {
		double d = newbytes / bytex;
		if (!"100.0%".equals(d)) {
			System.out.println(d);
		}
	}

	public static void main(String[] args) throws IOException, InterruptedException {
		File f1 = new File("C:\\Users\\Jack Smith\\Desktop\\Lyric\\2016年圣诞特辑.mp4");
		File f2 = new File("C:\\Users\\Jack Smith\\Desktop\\新建文件夹\\2016年圣诞特辑.mp4");
		new Q3().start();
		copy2(f1, f2);
	}
}

注:
    原创代码,如有雷同,纯属巧合
    代码有许多不足,欢迎留言讨论和更正

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值