前言
​​​​

Java内置类java.io.File类提供了多种创建文章的方式,在本文里我们会介绍其中的几种外加代码演示。
以下是File类提供的一些构造函数的介绍:

  1. File(String pathname):根据指定路径名创建File对象,路径名可以是相对路径或绝对路径。例如:File file = new File("example.txt");

  2. File(String parent, String child):根据指定的父路径和子路径创建File对象。例如:File file = new File("C:\Users\Admin", "example.txt");

  3. File(File parent, String child):根据指定的父文件和子路径名创建File对象。例如:File parent = new File("C:\Users\Admin"); File file = new File(parent, "example.txt");

  4. File(URI uri):根据指定的URI创建File对象。例如:File file = new File(new URI("file:///C:/Users/Admin/example.txt"));

方式1, 根据pathname创建

File(String pathname):根据指定路径名创建File对象,路径名可以是相对路径或绝对路径。例如:File file = new File("example.txt");

    @Test
    public void create01(){
        String filePath ="C:\\Users\\JinZh\\IdeaProjects\\TestJa\\software\\file01.txt";
        File file = new File(filePath);
        try {
            file.createNewFile();
            System.out.println("文件创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

方式2, 根据父路径+子路径创建

File(String parent, String child):根据指定的父路径和子路径创建File对象。例如:File file = new File("C:\Users\Admin", "example.txt");

    @Test
   public void create02(){
        File ParentFile = new File("C:\\Users\\JinZh\\IdeaProjects\\TestJa\\software\\");
        String fileName = "file02.txt";
        File file = new File(ParentFile, fileName);

        try {
            file.createNewFile();
            System.out.println("文件2创建成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

方式三,根据父目录文件+子路径创建

File(File parent, String child):根据指定的父文件和子路径名创建File对象。例如:File parent = new File("C:\Users\Admin"); File file = new File(parent, "example.txt");

    @Test
    public void create03(){
        String parentPath = "C:\\Users\\JinZh\\IdeaProjects\\TestJa\\";
        File parentFile = new File(parentPath);
        String childPath = "software\\file003.txt";
        File file = new File(parentFile, childPath);
        try {
            file.createNewFile();
            System.out.println("文件3创建成功");
        }catch (IOException e){
            e.printStackTrace();
        }
    }

获取文件信息

File类里也有很多方法可以帮助我们获取文件信息。

    @Test
    public void info(){
        File file = new File("C:\\Users\\JinZh\\IdeaProjects\\TestJa\\software\\file01.txt");
//        调用方法得到相应信息
        System.out.println("文件名: "+file.getName());
        System.out.println("文件绝对路径是: " + file.getAbsolutePath());
        System.out.println("文件父级目录:" + file.getParent());
    }

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐