来的比较迟,不知道还是否有分呢?
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author Administrator
*
* 将C盘指定的一个文件夹(包含文件夹内的所有文件夹和所有文件,多层嵌套)复制到D盘中
*/
public class CopyFile {
private static String folder;
public static void main(String[] args) {
//原文件路径
String path = "D:/test";
String[] strTemp = path.split("/");
folder = strTemp[strTemp.length - 1];
//复制到文件的路径
String copyPath = "E:";
//创建一个List集合,用于存放文件
List<MyFile> fileList = new ArrayList<MyFile>();
File file = new File(path);
//获取指定路径的文件或路径
File[] files = file.listFiles();
fileNameAndPath(files,fileList);
//复制文件
fileCopy(fileList,copyPath);
}
/**
* 将文件 复制到指定的路径下
* @param fileList
* @param copyPath
*/
private static void fileCopy(List<MyFile> fileList, String copyPath) {
for (MyFile myFile : fileList) {
String path = myFile.getOldPath() + File.separator + myFile.getName();
try {
//创建文件字节输入流
FileInputStream inputStream = new FileInputStream(path);
String newPath = copyPath + File.separator + myFile.getNewPath();
File file = new File(newPath);
if(!file.exists()){
//首先创建文件夹
file.mkdirs();
}
//再创建文件
String url = copyPath + File.separator + myFile.getNewPath() + File.separator + myFile.getName();
File newFile = new File(url);
if(!newFile.exists()){
newFile.createNewFile();
}
//创建文件字节输出流
FileOutputStream outputStream = new FileOutputStream(url);
int len = 0;
//创建缓存数组
byte[] buff = new byte[1024];
while((len = inputStream.read(buff)) != -1){
outputStream.write(buff, 0, len);
}
//关闭流对象
outputStream.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 将文件的路径和文件名称存放List集合当中
* @param file
* @param fileList
*/
private static void fileNameAndPath(File[] file, List<MyFile> fileList) {
for (int i = 0; i < file.length; i++) {
if(file[i].isFile()){
//是文件
String temp = file[i].getParent();
//获取第一次出现文件夹folder的下标索引位置
int index = temp.indexOf(folder);
fileList.add(new MyFile(temp,temp.substring(index),file[i].getName()));
}
if(file[i].isDirectory()){
File[] tempFile = file[i].listFiles();
fileNameAndPath(tempFile,fileList);
}
}
}
}
/**
*
* @author Administrator
* 用于存放文件信息
*/
class MyFile{
private String oldPath; //原来的文件路径
private String newPath; //复制后的文件路径
private String name; //文件名称
public MyFile(String oldPath, String newPath, String name) {
this.oldPath = oldPath;
this.newPath = newPath;
this.name = name;
}
public String getOldPath() {
return oldPath;
}
public void setOldPath(String oldPath) {
this.oldPath = oldPath;
}
public String getNewPath() {
return newPath;
}
public void setNewPath(String newPath) {
this.newPath = newPath;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
|