Java培训课程之File类的使用

1 File类

  • io.File类:文件和目录路径名的抽象表示形式,与平台无关
  • File 能新建、删除、重命名文件和目录,但 File 不能访问文件内容本身。如果需要访问文件内容本身,则需要使用输入/输出流。
  • File对象可以作为参数传递给流的构造器

 

2 File类的常见构造器

  • public File(String pathname)

以pathname为路径创建File对象,可以是绝对路径或者相对路径,如果pathname是相对路径,则默认的当前路径在系统属性user.dir中存储。

  • public File(String parent,String child)

以parent为父路径,child为子路径创建File对象。

  • File的静态属性String separator存储了当前系统的路径分隔符。
  • 在UNIX中,此字段为‘/’,在Windows中,为‘\\’

3 File类常用API

访问文件名

  • getName()
  • getPath()
  • getAbsoluteFile()
  • getAbsolutePath()
  • getParent()
  • toPath()
  • renameTo(File newName)

文件检测

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

获取常规文件信息

  • lastModified()
  • length()

文件操作相关

  • createNewFile()
  • delete()

目录操作相关

  • mkdir()
  • mkdirs()
  • delete()
  • list()
  • listFiles()

案例:

File dir1 = new File(“D:/IOTest/dir1”);

if (!dir1.exists()) {     // 如果D:/IOTest/dir1不存在,就创建为目录

       dir1.mkdir(); }

// 创建以dir1为父目录,名为”dir2″的File对象

File dir2 = new File(dir1, “dir2”);

if (!dir2.exists()) { // 如果还不存在,就创建为目录

       dir2.mkdirs(); }

File dir4 = new File(dir1, “dir3/dir4”);

if (!dir4.exists()) {

       dir4.mkdirs();

}

// 创建以dir2为父目录,名为”test.txt”的File对象

File file = new File(dir2, “test.txt”);    

if (!file.exists()) { // 如果还不存在,就创建为文件

       file.createNewFile();}

 


上一篇:
下一篇: