文件/目录部分处理工具类 DealDir.java

时间:2021-10-12 02:20:36
  1. package com.util;
  2. import java.io.File;
  3. import java.util.StringTokenizer;
  4. /**
  5. * 文件/目录 部分处理
  6. * @createTime Dec 25, 2010 7:06:58 AM
  7. * @version 1.0
  8. */
  9. public class DealDir {
  10. /**
  11. * 获取文件的后缀名并转化成大写
  12. *
  13. * @param fileName
  14. *            文件名
  15. * @return
  16. */
  17. public String getFileSuffix(String fileName) throws Exception {
  18. return fileName.substring(fileName.lastIndexOf(".") + 1,
  19. fileName.length()).toUpperCase();
  20. }
  21. /**
  22. * 创建多级目录
  23. *
  24. * @param path
  25. *            目录的绝对路径
  26. */
  27. public void createMultilevelDir(String path) {
  28. try {
  29. StringTokenizer st = new StringTokenizer(path, "/");
  30. String path1 = st.nextToken() + "/";
  31. String path2 = path1;
  32. while (st.hasMoreTokens()) {
  33. path1 = st.nextToken() + "/";
  34. path2 += path1;
  35. File inbox = new File(path2);
  36. if (!inbox.exists())
  37. inbox.mkdir();
  38. }
  39. } catch (Exception e) {
  40. System.out.println("目录创建失败" + e);
  41. e.printStackTrace();
  42. }
  43. }
  44. /**
  45. * 删除文件/目录(递归删除文件/目录)
  46. *
  47. * @param path
  48. *            文件或文件夹的绝对路径
  49. */
  50. public void deleteAll(String dirpath) {
  51. if (dirpath == null) {
  52. System.out.println("目录为空");
  53. } else {
  54. File path = new File(dirpath);
  55. try {
  56. if (!path.exists())
  57. return;// 目录不存在退出
  58. if (path.isFile()) // 如果是文件删除
  59. {
  60. path.delete();
  61. return;
  62. }
  63. File[] files = path.listFiles();// 如果目录中有文件递归删除文件
  64. for (int i = 0; i < files.length; i++) {
  65. deleteAll(files[i].getAbsolutePath());
  66. }
  67. path.delete();
  68. } catch (Exception e) {
  69. System.out.println("文件/目录 删除失败" + e);
  70. e.printStackTrace();
  71. }
  72. }
  73. }
  74. /**
  75. * 文件/目录 重命名
  76. *
  77. * @param oldPath
  78. *            原有路径(绝对路径)
  79. * @param newPath
  80. *            更新路径
  81. * @author lyf 注:不能修改上层次的目录
  82. */
  83. public void renameDir(String oldPath, String newPath) {
  84. File oldFile = new File(oldPath);// 文件或目录
  85. File newFile = new File(newPath);// 文件或目录
  86. try {
  87. boolean success = oldFile.renameTo(newFile);// 重命名
  88. if (!success) {
  89. System.out.println("重命名失败");
  90. } else {
  91. System.out.println("重命名成功");
  92. }
  93. } catch (RuntimeException e) {
  94. e.printStackTrace();
  95. }
  96. }
  97. }