zoukankan      html  css  js  c++  java
  • Java版本的删除指定目录及子目录下名叫“xxx.txt”的所有文件

    以前写过一个python版本的,但是在查找文件路径的时候出现错误,无法正确的获取到文件的路径,就造成无法删除该路径下的“xxx.txt”文件。

    当时以为是windows版本系统的错误造成这个问题的,也就没有继续深究,就把这个bug给放过了。

    最近一段时间在学习android,肯定要用的java了,就用java实现了下,思路的话,肯定还是以前的了,结果还是出错,后来仔细的看了看代码,其实是自己的bug。

    把代码贴下:(主要功能,删除指定目录下名叫"pylist.txt"的所有文件,使用递归和File类)

    版本1.使用file.list()获取到文件列表

     1 public class Example826 {
     2     /**
     3      * @param args
     4      *            删除指定目录和子目录下的指定文件
     5      */
     6     public static void main(String[] args) {
     7         String dir = "D:\PCsync\python";
     8         circleMethod(dir);
     9     }
    10 
    11     private static void circleMethod(String dirPath) {
    12         File file = new File(dirPath);
    13         if (file.isDirectory()) {
    14             String[] dirPathList = file.list();
    15             for (int i = 0; i < dirPathList.length; i++) {
    16                 String filePath = dirPath + File.separator + dirPathList[i];
    17                 File fileDelete = new File(filePath);
    18                 if (fileDelete.getName().equals("result.txt")) {
    19                     fileDelete.delete();
    20                 }
    21                 circleMethod(filePath);
    22             }
    23         }
    24     }
    25 
    26 }

     版本2.使用file.listFiles()获取所有子目录和文件

     1 public class Example826002 {
     2 
     3     /**
     4      * @param args
     5      *            删除指定目录和子目录下的的指定文件
     6      */
     7     public static void main(String[] args) {
     8         // TODO Auto-generated method stub
     9         String dir = "D:\PCsync\python";
    10         File file = new File(dir);
    11         circleMethod(file);
    12 
    13     }
    14 
    15     private static void circleMethod(File dir) {
    16 
    17         if (dir.isDirectory()) {
    18             File[] fileList = dir.listFiles();
    19             for (int i = 0; i < fileList.length; i++) {
    20                 circleMethod(fileList[i]);
    21             }
    22         } else {
    23 
    24             if (dir.getName().equals("xxx.txt")) {
    25                 System.out.println("文件名:" + dir.getAbsolutePath());
    26                 dir.delete();
    27                 System.out.println("该文件删除成功");
    28             }
    29         }
    30 
    31     }
    32 
    33 }
  • 相关阅读:
    connect oralce
    monolog php
    js继承
    前后端交互-一些关于接口设计的思考
    zoom:1;
    H5的新特性及部分API详解
    软文参考
    seo细节
    seo每天要做的事情
    seo(每天要干的哪些事)
  • 原文地址:https://www.cnblogs.com/liyiran/p/4771871.html
Copyright © 2011-2022 走看看