异常部门我是直接处理的,如果嫌麻烦的话也可向外抛出
闲话不多说,直接上代码。。。
package com.ListFile;
import java.io.*;
/**
* 统计文件个数
*/
public class CopyFile {
//定义一个外部变量,用于存放拷贝文件时穿件新的文件夹名称
public static String newFileName;
public static String address = "D";//定义拷贝地址的盘符
/**
* main方法
* @param args
*/
public static void main(String[] args) {
File file = new File("F:/test"); //传入想拷贝的文件的路径
count(file);
}
/**
* 递归实现拷贝
* @param file
*/
public static void count(File file){
if (null != file && file.exists()) {//递归头
//递归体
if (file.isFile()) {//如果是文件,直接拷贝
copy(file.getAbsolutePath(),newFileName);
}else{
for (File f : file.listFiles()){//如果是文件夹,在目标地址穿件新的文件夹
//构建新文件地址目录
String pathinname = f.getAbsolutePath();
String[] split = pathinname.split(":");
String s = split[0];
newFileName = pathinname.replaceFirst(s,address);
File newFile = new File(newFileName);
if (!newFile.exists()) {//判断这个新文件夹是否存在
if (f.isDirectory()){//如果源文件文件夹,则穿件新文件夹
//这里一定要用mkdirs() 不能用mkdir 不然创建路径时会抛异常
newFile.mkdirs();
}
if (f.isFile()){//如果源文件是文件,直接创建一个目标文件
try {
newFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
count(f);//递归调用
}
}
}
}
/**
* 拷贝文件
* @param in
* @param out
*/
public static void copy(String in,String out){
File fileIn = new File(in);//输入源
File fileOut = new File(out);//输出源
InputStream is= null;
OutputStream os = null;
try {
is = new FileInputStream(fileIn);
os = new FileOutputStream(fileOut);
byte[] flash = new byte[1024];
int len = -1;
while ((len = is.read(flash))!=-1){
os.write(flash,0,len);
}
os.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
来源:CSDN
作者:squad、小柒
链接:https://blog.csdn.net/squad/article/details/103926031