File文件 、递归

File

在这里插入图片描述
1.File 的概述
File:它是文件和目录路径名的抽象表示

  • 文件和目录是可以通过 File 封装成对象的
  • 对于 File 而言,其封装的不一定是一个真正存在的文件,仅仅是一个路径而已。它可以是存在的,也可以是不存在的。将来是要通过具体的操作把这个路径的内容转换为具体存在的

2.File 的构造方法

  • File(File parent, String child)
    从父抽象路径名和子路径名字符串创建新的 File实例

  • File(String pathname)
    通过将给定的路径名字符串转换为抽象路径名来创建新的 File实例

  • File(String parent, String child)
    从父路径名字符串和子路径名字符串创建新的 File实例

3.File 常用方法

创建功能
在这里插入图片描述
判断功能

public class FileDemo5 {

    public static void main(String[] args) throws IOException {

        File file = new File("D:\\tx.txt");
        //判断文件是否存在
        boolean exists = file.exists();
        System.out.println(exists);

        //判断这个文件对象是否是文件
        boolean isFile = file.isFile();
        System.out.println("判断一个文件对象是否是文件:"+isFile);


        //判断这个文件对象是否是目录
        boolean isDir = file.isDirectory();
        System.out.println("判断一个文件对象是否是目录:"+isDir);


        boolean absolute = file.isAbsolute();
        System.out.println("判断一个文件对象是否是绝对路径:"+absolute);


        File file1 = new File("D:\\aaa\\hello.txt");
        //判断文件是否可读
        boolean b = file1.canRead();
        System.out.println("文件是否可读:"+b);

        //判断文件是否可写
        boolean w = file1.canWrite();
        System.out.println("文件是否可写:"+w);


        //判断文件是否是隐藏的
        boolean h = file1.isHidden();
        System.out.println("文件是否隐藏:"+h);

    }
}

获取功能

public class FileDemo6 {

    public static void main(String[] args) throws IOException {

        File file = new File("D:\\tx.txt");
        //获得文件的绝对路径
        String absolutePath = file.getAbsolutePath();
        System.out.println("文件的绝对路径是:"+absolutePath);

        //创建一个文件对象,用相对路径, 相对路径就是当前的项目的跟路径
        File file1 = new File("a.txt");
        //file1.createNewFile();
        String absolutePath1 = file1.getAbsolutePath();
        System.out.println("文件的绝对路径是:"+absolutePath1);

        //获得的就是当前文件对象的路径
        String path = file1.getPath();
        System.out.println("文件的路径是:"+path);

        //获得文件名
        String name = file1.getName();
        System.out.println("获得文件名:"+name);

        //获得a.txt的大小
        long length = file1.length();
        System.out.println("文件的大小是:"+length);

        //获得最后的修改时间
        long l = file1.lastModified();
        System.out.println("文件的最后修改时间:"+l);
    }
}
String[] list() 
返回一个字符串数组,命名由此抽象路径名表示的目录中的文件和目录 

File[] listFiles() 
返回一个抽象路径名数组,表示由该抽象路径名表示的目录中的文件 

注意:list() 不能调用getName()方法,所以不能做是否是文件的判断,而listFiles()可以

删除功能

public class FileDemo4 {

    public static void main(String[] args) throws IOException {
        /*File file = new File("D:\\tx.txt");
        //程序删除不走回收站
        file.delete();
*/
        //删除路径的最后一层, 只有空目录才能被删除
        File file1 = new File("D:\\aaa\\bbb");
        boolean delete = file1.delete();
        System.out.println(delete);

    }
}

4.小例题

/**
    题目:目录的子文件获取
*/
public class FileDemo7 {

    public static void main(String[] args) throws IOException {

        //获得电脑磁盘的跟目录
        File[] files = File.listRoots();
        System.out.println(Arrays.toString(files));

        //获得一个目录下的子文件对象
        File file1 = new File("D:\\aaa");
        //获得D:\aaa下的子文件对象
        File[] files1 = file1.listFiles();
        for (File f : files1){
            System.out.println(f);
        }

        //获得子文件的名字
        String[] list = file1.list();
        System.out.println(Arrays.toString(list));


    }
}

递归

1.概述

以编程的角度来看,递归指的是方法定义中调用方法本身的现象

递归解决问题的思路:

  • 把一个复杂的问题层层转化为一个与原问题相似的规模较小的问题来求解
  • 递归策略只需少量的程序就可描述出解题过程所需要的多次重复计算

递归解决问题要找到两个内容:

  • 递归出口:否则会出现内存溢出
  • 递归规则:与原问题相似的规模较小

2.例题

求一个数的阶乘

public class FileDemo8 {

    public static void main(String[] args) throws IOException {

        int result = fn(5);
        System.out.println(result);
    }

    /**
     * 5! = 5*4!
     * 4! = 4*3!
     * 3! = 3*2!
     * 2! = 2*1!
     * 1! = 1
     *
     * fn(num) = num * fn(num - 1);
     *
     */
    public static int fn(int num){
        int result = 1;
        if(num > 1)
            //方法的自身调用自身就是递归
            result = num * fn(num - 1);
        return result;
    }
}

求十个数的阶乘和

/** 

 编写一个Java程序在屏幕上输出1!+2!+3!+..+10!的和
 
 */ 
 public static void main(String[] args){      
 //定义总和变量      
 int total=0;            
 for(int i=1;i<=10;i++){      
  //调用阶乘方法  累加  total=total+fn(i)       
  total += fn(i);      
  }     
  System.out.println(total); 
  }  
/**   
给定一个数,求这个数的阶乘   
5! = 5*4*3*2*1   
4! = 4*3*2*1  
3! = 3*2*1  
2! = 2*1  
1! = 1 */ 

public static int fn(int num){  
//定义结果变量  
int result=1;  
//变量参数就是我们指定的要进行阶乘的数  
//result=result*i  
for(int i=num;i>0;i--){      
//累乘     
result *= i;    
}  
return result;   
}
}

遍历和删除文件的两大例题

1.递归查询文件夹的内部所有文件?

public class FileDemo9 {

    //定义一个文件目录的层级
    static int level;

    public static void main(String[] args) throws IOException {
        //创建一个目录
        File file = new File("D:\\Program Files\\eclipse-jee-mars-1-win32-x86_64\\eclipse\\workspace\\demo1");
        parseFile(file);
    }

    public static void parseFile(File file){

        if(file == null || !file.exists()){
            return;
        }
        //给层级来加一
        level++;

        //获得文件对象的子文件对象列表
        File[] files = file.listFiles();
        //遍历这些子文件
        for(File f : files){
            //打印层级的缩进
            for (int i = 0; i < level; i++)
                System.out.print("\t");


            //打印文件
            System.out.println(f.getName());
            //判断这些子文件是否是目录
            if(f.isDirectory()){
                //递归的方式来遍历
                parseFile(f);
            }
        }
        //本层次遍历完毕把层级减回来
        level--;


    }
}

2.如何删除一个文件夹下的所有文件(不包括目录)?

public class FileDemo11 {

    //定义一个文件目录的层级
    static int level;

    public static void main(String[] args) throws IOException {
        //创建一个目录
        File file = new File("D:\\aaa");
        parseFile(file);
    }

    public static void parseFile(File file){

        if(file == null || !file.exists()){
            return;
        }

        //获得文件对象的子文件对象列表
        File[] files = file.listFiles();
        //遍历这些子文件
        for(File f : files){
            //判断这些子文件是否是目录
            if(f.isDirectory()){
                //递归的方式来遍历
                parseFile(f);
            }else {
                f.delete();
            }
        }
        //删除空文件夹
        file.delete();

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
// // FilePath.h // /** \file FilePath.h */ #pragma once #include "vtString.h" #include <fstream> #include <io.h> /** * A portable class for reading directory contents. * * Example of use: \code for (dir_iter it("C:/temp"); it != dir_iter(); ++it) { if (it.is_hidden()) continue; if (it.is_directory()) printf("Directory: '%s'\n", it.filename().c_str()); else printf("File: '%s'\n", it.filename().c_str()); } \endcode */ class dir_iter { public: dir_iter(); dir_iter(const char*dirname); dir_iter(const wchar_t*dirname); ~dir_iter(); /// Returns true if the current object is a directory. bool is_directory(); /// Returns true if the current object is hidden. bool is_hidden(); /// Get the filename fo the current object. std::string filename(); std::wstring wfilename(); // Iterate the object to the next file/directory. void operator++(); // Test for inequality useful to test when iteration is finished. bool operator!=(const dir_iter &it;); long m_handle; private: struct _wfinddata_t m_data; }; //MBCS string 或者 Wide string vtString vtFindFileOnPaths(const vtStringArray &paths;, const char *filename); vtString2 vtFindFileOnPaths(const vtStringArray2 &paths;, const wchar_t *filename); bool vtCreateDir(const char *dirname); bool vtCreateDir(const wchar_t *dirname); void vtDestroyDir(const char *dirname); void vtDestroyDir(const wchar_t *dirname); int vtDeleteFile(const char *filename); int vtDeleteFile(const wchar_t *filename); const char *vtStartOfFileName(const char *szFullPath); const wchar_t *vtStartOfFileName(const wchar_t *szFullPath); vtString vtExtractPath(const char *szFullPath, bool bTrailingSlash); vtString2 vtExtractPath(const wchar_t *szFullPath, bool bTrailingSlash); bool vtPathIsAbsolute(const char *szPath); bool vtPathIsAbsolute(const wchar_t *szPath); vtString vtPathLevelUp(const char *src); vtString2 vtPathLevelUp(const wchar_t *src); vtString get_line_from_stream(std::ifstream &input;); vtString2 get_line_from_stream(std::wifstream &input;); //bFull为ture包括所有扩展名;否则最后一个扩展名 void vtRemoveFileExtensions(vtString& fname,bool bFull = false); void vtRemoveFileExtensions(vtString2& fname,bool bFull = false); //bFull为ture包括所有扩展名;否则最后一个扩展名 vtString vtGetExtensions(const vtString &fname;, bool bFull = false); vtString2 vtGetExtensions(const vtString2 &fname;, bool bFull = false); bool vtChangeFileExtension(vtString& input, const char *extension); bool vtChangeFileExtension(vtString2& input, const wchar_t *extension); bool vtFileExists(const char *fname); bool vtFileExists(const wchar_t *fname); #pragma comment(lib, "shell32.lib") bool vtCopyFile( const char* from,const char * to, bool bFailIfExists=true); bool vtCopyFile( const wchar_t* from,const wchar_t * to, bool bFailIfExists=true); bool vtCopyTree(const char* from,const char * to); bool vtCopyTree(const wchar_t* from,const wchar_t * to); bool vtFolderExists(const char *fname); bool vtFolderExists(const wchar_t *fname); bool vtFilePathExists(const char *fname); bool vtFilePathExists(const wchar_t *fname); int vtGetFileSize(const char *fname); int vtGetFileSize(const wchar_t *fname); void vtSetEnvironmentVar(const char* var, const char*value); void vtSetEnvironmentVar(const wchar_t* var, const wchar_t*value); #include "windows.h" bool vtGetModuleFullPath(const char* modulename,vtString& fullpath); bool vtGetModuleFullPath(const wchar_t* modulename,vtString2& fullpath); ///////////////////////////////////////////// // Open a file using a UTF-8 or wide character filename. FILE *vtFileOpen(const char *fname_mbcs, const char *mode); FILE *vtFileOpen(const wchar_t *fname_wide, const wchar_t *mode); vtString vtChooseFolder(HWND hWnd =NULL); vtString2 vtChooseFolder2(HWND hWnd=NULL);

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值