package com.xyq.io.simply.core;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.FileVisitor;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
import java.util.List;
import com.xyq.io.enums.FileTypeMode;
import com.xyq.io.enums.OptionFile_TYPE;
import com.xyq.io.inf.NewNIoInf;
import com.xyq.io.util.FindFileUtil;
import com.xyq.io.util.MD5Util;
public class NewNIO implements NewNIoInf {
/***
* 拷贝或者移动文件
*/
@Override
public boolean copeOrMoveFile(String src, String tar, OptionFile_TYPE type) {
return realCopeOrMoveFile(Paths.get(src), tar, type);
}
private boolean realCopeOrMoveFile(Path srcPath, String tar,
OptionFile_TYPE type) {
Path tarPath = null;
boolean copeSuccess = true;
// 必须原始文件存在
if (srcPath.toFile().exists()) {
/***
* 如果原始路径是带斜杠的那么就认为这是一个文件夹
*/
if (isDir(tar))
tarPath = Paths.get(tar + File.separator
+ srcPath.toFile().getName());
else
tarPath = Paths.get(tar);
/***
* 然后进行N次(可以作为参数)拷贝操作(出错重连),是否覆盖拷贝,拷贝属性,拷贝操作不能使用回滚选项
*/
for (int i = 0; i < 3; i++) {
/***
* 如果是目标文件已经存在
*/
if (tarPath.toFile().exists()) {
/***
* 如果验证两个文件夹是相同的,拷贝选项下就不用拷贝,移动选项下就是删除原始文件
*/
// 拷贝
if (OptionFile_TYPE.COPE.equals(type)) {
if (equalsFile(srcPath.toFile(), tarPath.toFile()))
return true;
else
copeSuccess = copeFile(srcPath, tarPath, true);
}
/***
* 移动操作,这里得非常小心,正常情况下,如果两个文件是一样的话,
* 那么直接删除原始文件就可以了。但是,如果两个文件的一样,并且地址也
* 是一样的话,那么就不能删除原始的了,因为就是同一个文件,不能删除的。
*/
else if (OptionFile_TYPE.MOVE.equals(type)) {
if (equalsFile(srcPath.toFile(), tarPath.toFile())) {
if (!srcPath.toFile().getAbsoluteFile()
.equals(tarPath.toFile().getAbsoluteFile()))
try {
Files.delete(srcPath);
/***
* 之所以要手动指向true,是因为可能存在前面删除失败的情况
*/
if (!copeSuccess)
copeSuccess = true;
} catch (IOException e) {
copeSuccess = false;
}
// 前面因为有异常的可能就不直接return,这里就可以了
else
return true;
} else
copeSuccess = moveFile(srcPath, tarPath);
}
}
/***
* 当目标文件不存在的时候,先判断父类文件夹是可创 建(父类文件夹存在或者可以创建),可创建时就创建
*/
else {
File par = tarPath.getParent().toFile();
/***
* 如果父类文件夹不存在并且无法创建,那么就不用拷贝了
*/
if (!par.exists() && !par.mkdirs())
copeSuccess = false;
else if (OptionFile_TYPE.COPE.equals(type))
copeSuccess = copeFile(srcPath, tarPath, false);
else if (OptionFile_TYPE.MOVE.equals(type))
copeSuccess = moveFile(srcPath, tarPath);
}
// 如果操作成功,跳出循环
if (copeSuccess)
break;
}
} else
copeSuccess = false;
return copeSuccess;
}
/****
* 拷贝文件
*/
private boolean copeFile(Path srcPath, Path tarPath, bo