File类整理

File类概述

File更应该叫做一个路径,是一个文件和目录路径名的抽象表示形式。

构造方法

  • File(String pathname):根据一个路径得到File对象 
package com.learn.io;

import java.io.File;
import java.io.IOException;

public class IoTest {
public static void main(String[] args) throws IOException {
    File file = new File("C:\\Users\\Administrator\\Desktop\\sss.txt");
    System.out.println(file.exists());
}

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

    这种构造方式,parent和child为变量,更加灵活

public static void main(String[] args) throws IOException {
    String parent="C:\\Users\\Administrator\\Desktop";
    String child="sss.txt";
    File file = new File(parent,child);
    System.out.println(file.exists());

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

  这种构造方式parent可以使用file类的一些方法(较String类型更强大)

public static void main(String[] args) throws IOException {
    File file1 = new File("C:\\Users\\Administrator\\Desktop");
    String child="sss.txt";
    File file = new File(file1, child);
    System.out.println(file.exists());
}

File类的创建方法

  • 在指定目录下创建指定文件

      若文件已存在则创建失败(或file路径不正确),返回false

public static void main(String[] args) throws IOException {
    File file = new File("C:\\Users\\Administrator\\Desktop\\sss.txt");
    boolean createNewFile = file.createNewFile();
    System.out.println(createNewFile);
}
  • 在指定目录下创建文件夹

    若文件夹已存在则创建失败(或file路径不正确),返回false

public static void main(String[] args) throws IOException {
    File file= new File("C:\\Users\\Administrator\\Desktop\\hijiahsi");
    boolean mkdir = file.mkdir();
    System.out.println(mkdir);
}
  • 创建多级文件夹

    如果父文件夹不存在,会帮你创建出来

public static void main(String[] args) throws IOException {
    File file= new File("C:\\Users\\Administrator\\Desktop\\xuweiwen\\hahaah");
    boolean mkdir = file.mkdirs();
    System.out.println(mkdir);
}

猜你喜欢

转载自www.cnblogs.com/xuww-blog/p/9438058.html