File类的概述

  • File更应该叫做一个路径,文件路径或者文件夹路径 ,路径分为绝对路径和相对路径

    • 绝对路径:是一个固定的路径,从盘符开始
    • 相对路径:相对于某个位置,在eclipse下是指当前项目下,在dos下

      构造方法

      image.png
      File(String pathname):根据一个路径得到File对象

      1. /**
      2. * File(String pathname):根据一个路径得到File对象
      3. */
      4. @Test
      5. public void demo1() {
      6. //
      7. File file = new File("folder_a\\a.txt");
      8. System.out.println(file.exists());//true
      9. File file2 = new File("b.txt");
      10. System.out.println(file2.exists());//true
      11. File file3 = new File("c.txt");
      12. System.out.println(file3.exists());//false
      13. }

      File(String parent, String child):根据一个目录和一个子文件/目录得到File对象

      1. /**
      2. * File(String parent, String child):根据一个目录和一个子文件/目录得到File对象
      3. */
      4. @Test
      5. public void demo2() {
      6. String parent = "folder_b\\sub_b";
      7. String child = "file.txt";
      8. File file = new File(parent,child);
      9. System.out.println(file.exists());//true
      10. }

      File(File parent, String child):根据一个父File对象和一个子文件/目录得到File对象

      1. /**
      2. * File(File parent, String child):根据一个父File对象和一个子文件/目录得到File对象
      3. */
      4. @Test
      5. public void demo3() {
      6. File parent = new File("folder_b\\sub_b");
      7. String child = "file.txt";
      8. File file = new File(parent, child);
      9. System.out.println(file.exists());//true
      10. System.out.println(parent.exists());//true
      11. }