Java 创建目录,移动文件,重命名文件名

灰太狼 2023-10-05 18:27 93阅读 0赞

前言

今天要使用Java File类,实现创建目录,移动文件,重命名文件名功能

代码实现

  1. @org.junit.Test
  2. public void mvFileTest() {
  3. String fileName = "test.txt";
  4. // 目标文件目录
  5. String cameraPath = "C:/develop/project/lmes/ftp_root/camera";
  6. // 源文件
  7. File sourceFile = new File("C:/develop/project/lmes/ftp_root/temp/" + fileName);
  8. // 检查源文件是否存在
  9. if (sourceFile.exists()) {
  10. // 目标目录
  11. File targetPath = new File(cameraPath);
  12. // 目标文件
  13. File targetFile = new File(sourceFile + fileName);
  14. try {
  15. // 判断目标目录是否存在,不存在创建目录
  16. if (!targetPath.isDirectory()) {
  17. /**
  18. * mkdir() 创建目录,例如:D:/a
  19. * mkdirs() 递归创建目录,例如:D:/a/b/c
  20. */
  21. targetPath.mkdirs();
  22. }
  23. // 判断目标目录下是否存在文件,存在则删除
  24. if (targetFile.exists()) {
  25. targetFile.delete();
  26. }
  27. // 移动文件
  28. if (sourceFile.renameTo(targetFile)) {
  29. System.out.println("移动文件成功");
  30. } else {
  31. System.out.println("移动文件失败");
  32. }
  33. } catch (Exception e) {
  34. e.printStackTrace();
  35. }
  36. } else {
  37. System.out.println("源文件不存在");
  38. }
  39. }

发表评论

表情:
评论列表 (有 0 条评论,93人围观)

还没有评论,来说两句吧...

相关阅读