Chinaunix首页 | 论坛 | 博客
  • 博客访问: 504560
  • 博文数量: 184
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1172
  • 用 户 组: 普通用户
  • 注册时间: 2016-06-21 13:40
个人简介

技术改变命运

文章分类

全部博文(184)

文章存档

2020年(16)

2017年(12)

2016年(156)

我的朋友

分类: Java

2016-12-04 15:37:33

题目描述:
实现一个工具类,该工具可实现copy功能,若被copy的对象是文件,程序将制定文件复制到制定目录下,如过被copy对象是目录,程序应将该目录及其目录下的所有文件复制到指令目录下。 
代码如下:

点击(此处)折叠或打开

  1. import java.io.*;
  2. public class cpft
  3. {
  4.     public static void copyFile(String dst,String src) throws IOException
  5.     {
  6.         FileOutputStream fos = null;
  7.         FileInputStream fis = null;    
  8.             fos = new FileOutputStream(dst+"\\"+src.substring(src.lastIndexOf('\\')+1));
  9.             fis = new FileInputStream(src);
  10.             int hasRead = 0;
  11.             byte[] bbuf = new byte[1024];
  12.             while ((hasRead = fis.read(bbuf)) > 0)
  13.             {
  14.                 
  15.                 fos.write(bbuf,0,hasRead);
  16.             }
  17.         
  18.     }
  19.     public static void copy(String dst,String src) throws IOException
  20.     {
  21.         File newFile = new File(src);
  22.         File[] fileList = newFile.listFiles();
  23.         //File dstFile = new File(dst+"//"+newFile.getName());
  24.         if (newFile.isFile())
  25.         {
  26.             
  27.             copyFile(dst,src);
  28.         }
  29.         else
  30.         {
  31.             File dstFile = new File(dst+"//"+newFile.getName());
  32.             if (!dstFile.exists())
  33.             {
  34.                 dstFile.mkdirs();
  35.             }
  36.             for (File file:fileList)
  37.             {
  38.                 if (file.isFile())
  39.                         copyFile(dstFile.getAbsolutePath(),file.getAbsolutePath());
  40.                 else
  41.                         copy(dstFile.getAbsolutePath(),file.getAbsolutePath());
  42.             }            
  43.         }
  44.     }
  45.     public static void main(String[] args) throws IOException
  46.     {
  47.         
  48.         String src = "F:\\paper";
  49.         String dst = "F:\\冰点文库";
  50.         copy(dst,src);
  51.         System.out.println("finished Copy");
  52.     }
  53. }
运行结果:(完成复制)
finished Copy



阅读(886) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~