复制文件:

    1. //设计一个方法---->文件复制
    2. public void copyFile(File file,String path){
    3. FileInputStream fis = null;
    4. FileOutputStream fos = null;
    5. try {
    6. File newFile = new File(path+"//"+file.getName());
    7. fis = new FileInputStream(file);
    8. fos = new FileOutputStream(newFile);
    9. byte[] b = new byte[1000];
    10. int count = fis.read(b);
    11. while(count!=-1){
    12. fos.write(b,0,count);
    13. fos.flush();
    14. count = fis.read(b);
    15. }
    16. System.out.println("复制成功!");
    17. } catch (IOException e) {
    18. e.printStackTrace();
    19. }finally{
    20. try {
    21. if(fis!=null) {
    22. fis.close();
    23. }
    24. } catch (IOException e) {
    25. e.printStackTrace();
    26. }
    27. try {//为了保证程序的健壮性 各自关各自的 不会因为一个出现异常另一个关不上
    28. if(fos!=null) {
    29. fos.close();
    30. }
    31. } catch (IOException e) {
    32. e.printStackTrace();
    33. }
    34. }
    35. }

    复制文件夹:

    1. //复制文件夹
    2. public void copyFiles(File file,String newPath){
    3. //获取当前file对象的绝对路径
    4. String oleFilePath = file.getAbsolutePath();//比如E://test//bbb
    5. String newFilePath = newPath+oleFilePath.split(":")[1];////拼接path得到新路径 D://test//test//bbb
    6. //创建一个新的file对象
    7. File newFile = new File(newFilePath);//此时路径为 D://test//test//bbb
    8. //获取当前传进来的file对象的所有子元素
    9. File[] files = file.listFiles();
    10. //判断当前传进来的file对象是文件夹还是文件
    11. if(files!=null){//子元素不为空 就是文件夹 所以先复制文件夹
    12. //再通过这个新的newFile对象 在硬盘上创建一个文件夹
    13. //当前的创建路径为 D://test//test//bbb 在D盘这个路径可能不存在所以需要用mkdirs();
    14. newFile.mkdirs();
    15. System.out.println(newFile.getName()+"文件夹复制完毕");
    16. //如果文件夹里面还有元素 继续复制
    17. if(files.length!=0){//只有file对象是文件夹时才会进行递归
    18. //所以这段代码可以放在文件夹的if分支里
    19. //还可以把if()中重复的 files!=null 这个判断条件省略
    20. for(File f:files) {
    21. this.copyFiles(f,newPath);//递归 将文件夹里的元素全部复制过来
    22. }
    23. }
    24. }else{//file是一个文件
    25. FileInputStream fis = null;
    26. FileOutputStream fos = null;
    27. try {
    28. fis = new FileInputStream(file);
    29. fos = new FileOutputStream(newFile);
    30. byte[] b = new byte[1024];
    31. int count = fis.read(b);
    32. while(count!=-1){
    33. fos.write(b,0,count);
    34. fos.flush();
    35. count = fis.read(b);
    36. }
    37. System.out.println(newFile.getName()+"文件复制完毕");
    38. } catch (IOException e) {
    39. e.printStackTrace();
    40. }finally{
    41. try {
    42. if(fis!=null) {
    43. fis.close();
    44. }
    45. } catch (IOException e) {
    46. e.printStackTrace();
    47. }
    48. try {
    49. if(fos!=null) {
    50. fos.close();
    51. }
    52. } catch (IOException e) {
    53. e.printStackTrace();
    54. }
    55. }
    56. }
    57. }