java获取某个文件夹下的所有文件、删除文件

た 入场券 2022-08-20 04:15 425阅读 0赞
  1. </pre><pre name="code" class="javascript">public static void main(String[] args) throws IOException {
  2. readFile("E:\\testFilePath");
  3. deleteFile("E:\\testFilePath");
  4. }
  5. /**
  6. * 获取文件路径,包括子文件夹下文件路径
  7. * @param filePath
  8. * @return
  9. */
  10. public static boolean readFile(String filePath) {
  11. File file = new File(filePath);
  12. if (!file.isDirectory()) {
  13. System.out.println("文件地址:" + file.getAbsolutePath());
  14. } else if (file.isDirectory()) {
  15. String[] fileList = file.list();
  16. for (int i = 0; i < fileList.length; i++) {
  17. File readfilePath = new File(filePath + "\\" + fileList[i]);
  18. if (!readfilePath.isDirectory()) {
  19. System.out.println("文件地址:" + readfilePath.getAbsolutePath());
  20. } else if (readfilePath.isDirectory()) {
  21. readFile(filePath + "\\" + fileList[i]);
  22. }
  23. }
  24. }
  25. return true;
  26. }
  27. /**
  28. * 删除文件夹下所有文件,包括子文件夹下文件
  29. * @param delpath
  30. * @return
  31. */
  32. public static boolean deleteFile(String delpath) {
  33. File filePath = new File(delpath);
  34. if (!filePath.isDirectory()) {
  35. filePath.delete();
  36. } else if (filePath.isDirectory()) {
  37. String[] fileList = filePath.list();
  38. for (int i = 0; i < fileList.length; i++) {
  39. File delfile = new File(delpath + "\\" + fileList[i]);
  40. if (!delfile.isDirectory()) {
  41. System.out.println("文件地址:"+delfile.getAbsolutePath());
  42. delfile.delete();
  43. System.out.println("删除文件成功");
  44. } else if (delfile.isDirectory()) {
  45. deleteFile(delpath + "\\" + fileList[i]);
  46. }
  47. }
  48. filePath.delete();
  49. }
  50. return true;
  51. }

发表评论

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

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

相关阅读