JAVA IO(二)File类详解

用途

File类用于表示目录或文件,只是描述目录或文件的信息,不能用于访问文件的内容。

常用方法

  • boolean mkdir();
  • boolean mkdirs();
  • boolean createNewFile();
  • boolean delete()
public void createDir(String dirPath) {
        File file   = new File(dirPath);
        if (!file.exists()) {
            file.mkdir();
        } else {
            file.delete();
        }
    }
  • boolean canExecute()
  • boolean canRead()
  • boolean canWrite()
  • boolean exists()
  • boolean isDirectory()
  • boolean isFile()
  • boolean isHidden()
  • boolean isAbsolute()
  • String getName()
  • String getPath()
  • String getAbsolutePath()
  • String getParent()
  • long lastModified()
  • long length()
  • boolean renameTo(File f)
  • File[] listFiles()
/**
     * @param dirPath
     * 列出所有的文件及子目录下文件
     */
    public void listAllFile(String dirPath) {
        File file   = new File(dirPath);
        if (!file.exists() || !file.isDirectory()) {
            System.out.println(dirPath + "is not exist or it's not a dir.");
            return;
        }
        listFiles(file);
    }

    public void listFiles(File currentFile) {
        if (!currentFile.exists()) {
            return;
        }

        File[] files    = currentFile.listFiles();
        for (File file: files) {
            if (file.isDirectory()) {
                listFiles(file);
            } else {
                System.out.println(file);
            }
        }
    }
  • String[] list()
  • String[] list(FilenameFilter filter)
    这两个方法返回的字符串数组,数组的内容是当前file路径下的文件或子目录名,如果file是个文件,则返回null;
    对于第二个方法,需要一个实现了FilenameFilter接口的类实例;
    public interface FilenameFilter {
        boolean accept(File dir, String name);
    }

这是一个典型的策略模式,在list中会调用filter的accept()方法,如果accept()返回的是true,这个文件或者目录就会包含在list()方法的返回值中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值