Java本地文件移动

一、采用流来处理文件的移动,这样会导致有两份文件需要删除

//fileSourcePath源文件路径 fileTargetPath目标文件路径
File file = new File(fileSourcePath);

String targetDirPath = fileTargetPath.substring(0, fileTargetPath.lastIndexOf("/"));
Path targetDir = Paths.get(targetDirPath);
// 如果目标文件夹不存在,则创建它
if (!Files.exists(targetDir)) {
    Files.createDirectories(targetDir);
}
File file1 = new File(fileTargetPath);
byte[] bytes = Files.readAllBytes(file.toPath());
FileOutputStream outputStream = new FileOutputStream(file1);
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
try {
	file.delete();
}catch (Exception e){
	
}

二、采用java.nio.file中的Files中的copy方法,有两份文件需要删除

try {
	//fileSourcePath源文件路径 fileTargetPath目标文件路径
	Path sourcePath = Paths.get(fileSourcePath);
	String targetDirPath = fileTargetPath.substring(0, fileTargetPath.lastIndexOf("/"));
	Path targetDir = Paths.get(targetDirPath);
	Path targetPath = Paths.get(fileTargetPath);
	
	// 如果目标文件夹不存在,则创建它
	if (!Files.exists(targetDir)) {
	    Files.createDirectories(targetDir);
	}
	
	// 移动文件,如果目标文件已存在,则替换它
	Files.copy(sourcePath, targetPath,StandardCopyOption.REPLACE_EXISTING);
	try {
		//文件执行拷贝时间需要等待,不然无法删除源文件
	    File file = new File(fileSourcePath);
	    file.delete();
	}catch (Exception e){
	
	}
	return true;
} catch (Exception e) {
	e.printStackTrace();
	System.out.println("移动图片时出现错误");
}

三、采用java.nio.file中的Files中的remove方法,不需要删除,但是源文件不能
处于使用状态,不然或出现异常;

try {
	Path sourcePath = Paths.get(fileSourcePath);
	String targetDirPath = fileTargetPath.substring(0, fileTargetPath.lastIndexOf("/"));
	Path targetDir = Paths.get(targetDirPath);
	Path targetPath = Paths.get(fileTargetPath);
	
	// 如果目标文件夹不存在,则创建它
	if (!Files.exists(targetDir)) {
	    Files.createDirectories(targetDir);
	}
	
	// 移动文件,如果目标文件已存在,则替换它
	Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
	e.printStackTrace();
	System.out.println("移动图片时出现错误");
}

以上就是我目前知道的三种方式,不足之处,还望勿怪;

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值