Java的copy文件和文件夹以及删除文件夹(包括递归与非递归算法)

时间:2021-11-07 21:39:48
 

Copy文件算法

 /**
* <pre>
* 复制文件
* 源文件不存在,直接返回
* 目标文件不存在时,创建父目录
* </pre>
*
* @param srcFile 源文件
* @param destFile 目标文件
*/
public static void copy(File srcFile, File destFile) {
//源文件不存在,直接返回
if (!srcFile.exists()) {
logger.info("源文件["+ srcFile.getName() +"]不存在");
return;
}
//目标文件不存在时,创建父目录
if (!destFile.exists()) {
logger.info("目标文件["+ destFile.getName() +"]所在的父目录不存在,创建父目录");
destFile.getParentFile().mkdirs();
}
FileInputStream fis = null;
BufferedInputStream bis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fis = new FileInputStream(srcFile);
bis = new BufferedInputStream(fis);
fos = new FileOutputStream(destFile);
bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024 * 5];

int length;
while ((length = bis.read(buffer)) != -1) {
bos.write(buffer, 0, length);
}
bos.flush();

} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
try {
if (fis != null) {
fis.close();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
try {
if (fos != null) {
fos.close();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
try {
if (bis != null) {
bis.close();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
try {
if (bos != null) {
bos.close();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
}
}


 

Copy目录(递归算法)

/**
* 复制目录下的所有到另一目录
* @param srcDir
* @param destDir
*/
public static void copyDir(File srcDir,File destDir){
//生成目录
if(!destDir.exists()){
destDir.mkdirs();
}
//循环源目录
File[]srcFiles = srcDir.listFiles();
for (int i = 0; i < srcFiles.length; i++) {
File src = srcFiles[i];
if(src.isFile()){
File targetFile = new File(destDir.getAbsolutePath() + "\\" + src.getName());
copy(src, targetFile);
}else{
copyDir(new File(srcDir + "\\" + src.getName()), new File(destDir + "\\" + src.getName()));
}
}
}

 

Copy目录(非递归算法):

 /**
* 拷贝目录(非递归)
* @param srcDir 源目录
* @param destDir 目标目录
*/
public static void copyDirNonRecursion(File srcDir, File destDir) {
//生成目录
if (!destDir.exists()) {
logger.info("目标文件["+ destDir.getName() +"]的目录不存在,创建相应目录");
destDir.mkdirs();
}

Stack<File> fileStack = new Stack<File>();
fileStack.push(srcDir);
File curFile;
File preFile = null;
String parentPath = destDir.getAbsolutePath();
parentPath = parentPath.replaceAll("[\\\\]", "/");
String srcPath = srcDir.getAbsolutePath();
while (!fileStack.empty()) {
curFile = fileStack.peek();
File[] fileLists = curFile.listFiles();
//当前文件为非目录,或者空目录或者前一个文件的父目录为当前文件时
if (curFile.isFile()
|| (preFile != null && (preFile.getParent().equals(curFile.getAbsolutePath())))
|| (fileLists.length == 0)) {
File popFile = fileStack.pop();
String filePath = popFile.getAbsolutePath();
if (filePath.equals(srcPath)) {
continue;
}
filePath = filePath.replaceAll("[\\\\]", "/");
filePath = filePath.substring(srcPath.length() + 1);
filePath = parentPath + "/" + filePath;
if (popFile.isFile()) {
copy(popFile, new File(filePath));
} else {
File dir = new File(filePath);
dir.mkdirs();
}
preFile = curFile;
} else {
for (File file : fileLists) {
fileStack.push(file);
}
}
}
}


 


删除目录(递归算法)

/**
* 给入一个目录,删除该目录下的所有文件。
* @param dir
*/
public static void deleteDir(File dir){
if(dir.isDirectory()){
File[] listFiles = dir.listFiles();
for (int i = 0; i < listFiles.length; i++) {
File f = listFiles[i];
if(f.isFile()){
f.delete();
} else if(f.isDirectory()){
deleteDir(f);
}
}
//删除当前目录
dir.delete();
}
}


 

 删除目录(非递归算法):

    /**
* 删除目录(非递归)
* @param srcDir 源目录
*/
public static void deleteDirNonRecursion(File srcDir) {
Stack<File> fileStack = new Stack<File>();
fileStack.push(srcDir);
File curFile;
File preFile = null;
while (!fileStack.empty()) {
curFile = fileStack.peek();
File[] fileLists = curFile.listFiles();
//当前文件为非目录,或者空目录或者前一个文件的父目录为当前文件时
if (curFile.isFile()
|| (preFile != null && (preFile.getParent().equals(curFile.getAbsolutePath())))
|| (fileLists.length == 0)) {
File popFile = fileStack.pop();
popFile.delete();
preFile = curFile;
} else {
for (File file : fileLists) {
fileStack.push(file);
}
}
}
}


 

读取目录(非递归算法):

public void readFile(File rootFile) {
Stack<File> fileStack = new Stack<File>();
fileStack.push(rootFile);
File curFile;
File preFile = null;
while (!fileStack.empty()) {
curFile = fileStack.peek();
File[] fileLists = curFile.listFiles();
if (curFile.isFile()
|| (preFile != null && (preFile.getParent().equals(curFile.getAbsolutePath())))
|| (fileLists.length == 0)) {
System.err.println(curFile.getAbsolutePath());
fileStack.pop();
preFile = curFile;
} else {
for (File file : fileLists) {
fileStack.push(file);
}
}
}
}