使用Java的多线程和IO流写一个文件复制功能类
2016-07-21 15:44
706 查看
创建一个复制功能类,继承Thread类,重写run()方法,把FileInputStream和FileOutputStream输入输出流写在run()方法内。示例代码如下:
在测试类中调用复制功能类
import java.io.*; import java.text.DecimalFormat; /** * 文件复制类 * @author Administrator * */ public class FileCopy extends Thread { private File src;//待读取的源文件 private File dest;//待写入的目标文件 public FileCopy(String src,String dest){ this.src = new File(src); this.dest = new File(dest); } @Override public void run() { FileInputStream is = null; FileOutputStream os = null; try { is = new FileInputStream(src); os = new FileOutputStream(dest); byte[] b = new byte[1024]; int length = 0; //获取源文件大小 long len = src.length(); //已复制文件的字节数 double temp = 0 ; //数字格式化,显示百分比 DecimalFormat df = new DecimalFormat("##.00%"); while((length = is.read(b))!=-1){ //输出字节 os.write(b, 0, length); //获取已下载的大小,并且转换成百分比 temp += length; double d = temp/len; System.out.println(src.getName()+"已复制的进度:"+df.format(d)); } System.out.println(src.getName()+"复制完成!"); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { if (is != null) { is.close(); } if(os!=null){ os.close(); } } catch (Exception e) { e.printStackTrace(); } } } }
在测试类中调用复制功能类
public class FileCopyTest { public static void main(String[] args) { FileCopy cf = new FileCopy("D:\\720.txt","D:\\test\\1.txt"); FileCopy cf2 = new FileCopy("D:\\721.txt","D:\\test\\2.txt"); FileCopy cf3 = new FileCopy("D:\\123.txt","D:\\test\\3.txt"); cf.start(); cf2.start(); cf3.start(); } }
相关文章推荐
- springmvc+easyUI的DataGrid分页功能
- java并发库_并发库知识点整理
- 利用java实现二维码和背景图的合并
- JAVA写的网页爬虫爬取必应词典的词汇音标
- Java内存溢出详解
- Jersey+Spring+Hibernate搭建的一个简单Web Service
- Spring MVC Web简单入门实例
- 通过JDBC获取表结构生成javaBean
- Java经典设计模式:七大结构型模式(附实例和详解)
- org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component c
- Spring 整合javaWeb项目导入的lib包
- MyEclipse启动时出现异常:An internal error occurred during: "Updating indexes".
- 教给你如何使用Java8数据流
- Eclipse安装Hibernate tools插件自动生成代码
- spring整合mybatis
- Java中的IO技术使用总结
- 在eclipse上搭建Ionic环境
- 细数JDK里的设计模式
- Map(二)之LinkedHashMap(java8)
- 解决Cannot change version of project facet Dynamic web module to 2.5