将一个文件夹复制到另一个地方

public static void copyFile(String srcname,String target) throws Exception{
		File srcfile = new File(srcname);
        //将原文件目录在目标文件夹下创建
		File targfile = new File(target,srcfile.getName());
		targfile.mkdirs();
        //获取源文件夹下文件集合
		File[] files = srcfile.listFiles();
        //遍历集合
		if (files!=null) {
			for (File file : files) {
				if (file.isFile()) {
                //创建输入输出流,小数组进行复制
				FileInputStream fis = new FileInputStream(file);
				File fo = new File(targfile, file.getName());
				FileOutputStream fos = new FileOutputStream(fo);
				int len;
				byte[] bs = new byte[1024];
				while((len=fis.read(bs))!=-1) {
					fos.write(bs, 0, len);
				}
				fis.close();
				fos.close();
				}else if (file.isDirectory()) {
                    //递归方式重新遍历子文件夹下的文件,注意要获取绝对路径
					copyFile(file.getAbsolutePath(), targfile.getAbsolutePath());
				}
			}
		}
				
	}

注意:在递归时要获取绝对路径

猜你喜欢

转载自blog.csdn.net/moxiaomo0804/article/details/89544938