随手写个删除文件demo

2019-03-28 10:27:48
  1. import java.io.IOException;
  2. import java.nio.file.DirectoryStream;
  3. import java.nio.file.Files;
  4. import java.nio.file.Path;
  5. import java.nio.file.Paths;
  6. /**
  7. * 文件删除测试类
  8. *
  9. * @author wangjing
  10. * @version 1.0 created 2019/3/25
  11. */
  12. public class DelFileTest {
  13. public static void main(String[] args) {
  14. Path path = Paths.get("/Users/wangjing/Downloads/Contents");
  15. System.out.println(path.toFile().getAbsolutePath());
  16. try {
  17. deleteAllFile(path);
  18. } catch (IOException e) {
  19. e.printStackTrace();
  20. }
  21. }
  22. /**
  23. * 删除文件
  24. *
  25. * @param path
  26. * @return
  27. * @author wangjing
  28. * @date: 上午10:49 2019/3/27
  29. */
  30. public static void deleteAllFile(Path path) throws IOException {
  31. //如果是文件直接删除
  32. if (!Files.isDirectory(path)) {
  33. Files.deleteIfExists(path);
  34. return;
  35. }
  36. //获取文件夹下所有文件进行遍历递归删除
  37. try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(path)) {
  38. for (Path dirFilePath : directoryStream) {
  39. //如果是文件夹则继续递归
  40. if (Files.isDirectory(dirFilePath)) {
  41. deleteAllFile(dirFilePath);
  42. } else {
  43. //是文件则删除
  44. Files.deleteIfExists(dirFilePath);
  45. }
  46. }
  47. //删除空文件夹
  48. Files.deleteIfExists(path);
  49. }
  50. }
  51. }

0
2
0

添加评论

正在回复:
取消
0
0
2
0