Java之file类

Java的file类,操作文件。mkdir创建单机目录,mkdirs创建多级目录。getparent返回父目录路径,getpath返回文件的相对路径。creatnewfile用于创建文件

package com.company;
import java.io.File;
public class Main {
    public static void main(String[] args) {
    // write your code here
        File file=new File("College\Department\Class");
        if (!file.exists()){
            file.mkdirs();
            System.out.println("目录创建成功");
            System.out.println(file.getPath());
        }
    }
}

输出:

目录创建成功
CollegeDepartmentClass
Process finished with exit code 0

案例:

package com.company;

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

/**
 * @author 红塔集团
 * @date 2019/1/1910:53
 * 创建文件,并判断可读与否
 */
public class imooc_2_7 {
    public static void main(String[] args) {
        File file=new File("F:\test");
        if (!file.exists()){
            file.mkdirs();
        }
        File Monday=new File("F:\test\Monday.docx");
        if (!Monday.exists()){
            try {
                Monday.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("文件创建成功了");
        System.out.println("文件名称是:"+Monday.getName());
        System.out.println("文件的上一级目录是:"+Monday.getParent());
        if (Monday.isFile()){
            System.out.println("文件/目录:这是一个文件");
        }
        if (Monday.canRead()){
            if (Monday.canWrite()){
                System.out.println("读写性:这个文件可读可写");
            }
        }

    }
}
原文地址:https://www.cnblogs.com/cquer-xjtuer-lys/p/10290891.html