java 7 nio2 copy_使用jdk7的nio2操作文件拷贝和剪切示例

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值