记录IO复制文件极其子文件 遇到的问题

package com.baidu.Collection;

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

public class Test4 {
    public static void copyFile(String srcPath,String destPath){
        File srcFile=new File(srcPath);
        File destFile=new File(destPath);
       ***destFile.getParentFile().mkdirs();***
        byte[] buffer=new byte[1024];
        try(FileInputStream fis=new FileInputStream(srcFile);
            **FileOutputStream fos=new FileOutputStream(destFile)**;
        ){
            while (srcFile != null) {
                int length=fis.read(buffer);
                if(length==-1)
                    break;
                fos.write(buffer,0,length);
                fos.flush();
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
    public static void **copyDirectory(String srcPath,String destPath)**{
        File src=new File(srcPath);
        File dest=new File(destPath);
        File[] files=src.listFiles();
        for(File each:files){
            if(each.isFile())
            {
                File s=new File(destPath,each.getName());
                copyFile(each.getAbsolutePath(),s.getAbsolutePath());}
            if(each.isDirectory()){
                File s=new File(**destPath,each.getName());**
                copyDirectory(each.getAbsolutePath(),s.getAbsolutePath());
            }

        }
    }
    public static void main(String[] args) {
        copyDirectory("d:/1","d:/2");
    }
}

调试了好久,代码终于通了,总结一下。
1.destFile.getParentFile().mkdirs();
①mkdirs()会帮你建立这个文件夹,注意假如是d:/1/2/1.txt这样的目录,1.txt默认也是文件夹。
2. FileOutputStream fos=new FileOutputStream(destFile),
①输出流会帮你建立文件,但是不会帮你建立上级目录,上级目录必须存在才行。所以在写的时候,报了FileNotFound
②输出流写到文件夹会报”拒绝访问“的错误,之前创了个文件目录,所以老报这个错。
3.copyDirectory(String srcPath,String destPath)
destPath,each.getName());
①despath,我之前直接里面放的destPath+each.getName(),注意!!‘ / ’文件目录这个符号忘了,还是用那个文件的有参构造器比较好。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值