首页 > 技术文章 > Java File类

xiafrog 2021-01-17 16:57 原文

Java File类

  • File类对象代表文件或文件目录

构造器

  • File(String pathname)
    • 相对路径:相对于当前module,若为静态方法,则相对于当前工程
    • 绝对路径:"\"需要用"\\"来转义,Linux和URL中使用"/"
      • 也可以直接使用File.seperator来代替斜杠
  • File(String parent, String child)
  • FIle(File parent, String child)

常用方法

获取功能:

  • String getAbsolutePath()
  • String getPath()
  • String getName()
  • String getParent():获取上层目录,不存在(相对路径)则为null
  • long length():获取文件长度(字节数),不能用于目录
  • long lastModified():获取最后一次修改时间,单位毫秒
  • String[] list():获取指定目录下的文件和目录名称
  • File[] listFiles():获取指定目录下的文件和目录的FIle对象

重命名功能:

  • boolean renameTo(File dest):把文件重命名为指定的路径,目标文件不能存在

判断功能:

  • boolean isDirectory()
  • boolean isFile()
  • boolean exists()
  • boolean canRead()
  • boolean canWrite()
  • boolean isHidden()

创建功能:

  • boolean createNewFile():若文件存在,返回flase
  • boolean mkdir():若目录存在或上层目录不存在,都不创建
  • boolean mkdirs():若上层目录不存在,一并创建

删除功能:

  • boolean delete():删除的文件目录内不能包含文件或文件目录

推荐阅读