Java中File类的基本用法

File类的基本用法

  java.io.File类:代表文件和目录。在开发中,读取文件、生成文件、删除文件、修改文件的属性时经常会用到此类。

File类的常用构造方法:public File(String pathname)

  以pathname为路径创建File对象,如果pathname是相对路径,则默认的当前路径在系统属性user.dir中存储。

文件的创建

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

public class Test {
    public static void main(String[] args) throws IOException {
        System.out.println(System.getProperty("user.dir")); //输出当前工程的绝对路径
        File f1 = new File("a.txt");    //相对路径,默认目录在System.out.println(System.getProperty("user.dir"));
        boolean flag1 = f1.createNewFile();
        System.out.println(flag1);
        File f2 = new File("F:/b.txt"); //绝对路径
        boolean flag2 = f2.createNewFile();
        System.out.println(flag2);
    }
}
//输出
G:\IntelliJ IDEA 2018.2.4\IdeaProjects
true
true

通过FIle类对象可以访问文件的属性:

  表8-3 File类访问属性的方法列表

通过File对象创建空文件或目录(在该对象所指的文件或目录不存在的情况下)

表8-4 File类创建文件或目录的方法列表

 

猜你喜欢

转载自www.cnblogs.com/chiweiming/p/11308229.html