File类用于新建、删除、重命名文件或者目录,但不能够访问其内容,访问内容需要使用输入/输出流。File类用路径字符串来创建File实例,路径可以是绝对或相对路径,系统通过用户的工作路径来解释相对路径(通常为运行Java虚拟机是所在的路径)。

public class FileTest {
    public static void main(String[] args) throws IOException {
        // 以当前路径来创建一个File对象
        File file = new File(".");
        // .
        System.out.println(file.getName());
        // 获取相对路径的父路径,null
        System.out.println(file.getParent());
        // E:\javaworkplace\20210509\.
        System.out.println(file.getAbsolutePath());
        // E:\javaworkplace\20210509
        System.out.println(file.getAbsoluteFile().getParent());
        // 当前路径下创建一个临时文件
        File tmpFile = File.createTempFile("aaa", ".txt", file);
        // delete when JVM exit
        tmpFile.deleteOnExit();
        File newFile = new File(System.currentTimeMillis() + "");
        // Does new File exists:false
        System.out.println("Does new File exists:" + newFile.exists());
        newFile.createNewFile();
        // Does new File exists:true
        System.out.println("Does new File exists:" + newFile.exists());
        // newFile exists,can't use newFile to generate dictory, return false.
        System.out.println(newFile.mkdir());
        String[] fileList = file.list();
        System.out
                .println("==all files and dictories under contemporary path==");
        for (String fileName : fileList) {
            System.out.println(fileName);
        }
        File[] roots = File.listRoots();
        System.out.println("==all system root path==");
        // C:\
        // D:\
        // E:\
        for (File root : roots) {
            System.out.println(root);
        }
    }
}