zoukankan      html  css  js  c++  java
  • 利用File类递归找或删除到目录下所有文件

    Java中对文件的操作借助于File类,具体请看jdk文档或别人的博客。

    说一下以下代码用到的方法:

    File.listFiles() 以File数组的形式返回文件夹下所有File对象

    File.isDirectory() 判断File对象是否为文件夹

    File.delete() 删除File对象(注意不是放到回收站,而是直接擦除空间,慎用)。若File对象正在被别的程序使用,或者包含其他文件或文件夹,该方法无法实现。

    使用递归的方法遍历文件夹:

    因为位置文件夹的结构,所以要递归知道没有文件夹为止

     1 package com.hlyc.Stream;
     2 
     3 import java.io.File;
     4 
     5 public class select {
     6     int i;
     7     public static void main(String args[]){
     8         
     9         File file = new File("D:/啊啊啊");
    10         getAllFiles(file);
    11     }
    12     //遍历方法
    13     public static void getAllFiles(File file){
    14         if(file == null)
    15             return ;
    16         if(file.isDirectory()){
    17             File[] files = file.listFiles();
    18             if(files != null){
    19                 for(File f : files)
    20                     getAllFiles(f);
    21             }
    22         }
    23         //获得想要的后缀文件名
    24         if(file.getName().endsWith(".rmvb") || file.getName().endsWith(".mp4"))
    25             System.out.println(file.getName());
    26         
    27     }
    28     //删除的方法
    29     public static void deleteAllFiles(File file){
    30         if(file == null || !file.exists())
    31             return ;
    32         if(file.isDirectory()){
    33             File[] files = file.listFiles();
    34             if(files != null){
    35                 for(File f : files)
    36                     deleteAllFiles(f);
    37             }
    38         }
    39         file.delete();
    40     }
    41 }
  • 相关阅读:
    批处理实现SQLServer数据库备份与还原
    Axapta物流模块深度历险(二)
    Axapta4.0Tech
    Script#
    Axapta物流模块深度历险(一)
    Agrs Class
    折半的意义
    个人性格
    诚实
    英语学习闪存
  • 原文地址:https://www.cnblogs.com/cxy2016/p/7157287.html
Copyright © 2011-2022 走看看