前言
今天要使用Java File类,实现创建目录,移动文件,重命名文件名功能
代码实现
@org.junit.Test
public void mvFileTest() {
String fileName = "test.txt";
// 目标文件目录
String cameraPath = "C:/develop/project/lmes/ftp_root/camera";
// 源文件
File sourceFile = new File("C:/develop/project/lmes/ftp_root/temp/" + fileName);
// 检查源文件是否存在
if (sourceFile.exists()) {
// 目标目录
File targetPath = new File(cameraPath);
// 目标文件
File targetFile = new File(sourceFile + fileName);
try {
// 判断目标目录是否存在,不存在创建目录
if (!targetPath.isDirectory()) {
/**
* mkdir() 创建目录,例如:D:/a
* mkdirs() 递归创建目录,例如:D:/a/b/c
*/
targetPath.mkdirs();
}
// 判断目标目录下是否存在文件,存在则删除
if (targetFile.exists()) {
targetFile.delete();
}
// 移动文件
if (sourceFile.renameTo(targetFile)) {
System.out.println("移动文件成功");
} else {
System.out.println("移动文件失败");
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
System.out.println("源文件不存在");
}
}