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类创建文件或目录的方法列表

 

 

 递归遍历目录的所有文件

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

public class Test {
    public static void main(String[] args) throws IOException {
        File f1 = new File("E:/系统");
        printDir(f1,0);
    }
    public static void printDir(File file,int level){
        for (int i = 0; i < level; i++) {
            System.out.print("-");
        }
        System.out.println(file.getName());
        if(file.isDirectory()){ //如果是目录
            File files[] = file.listFiles();    //列出当前目录下的所有文件
            for (int i = 0; i < files.length; i++) {    //递归遍历当前目录下的所有文件
                printDir(files[i],level+1);
            }
        }

    }
}
//输出
系统
-W10系统
--UserData
---Desktop
----desktop.ini
---desktop.ini
---Documents
----desktop.ini
----My Music
----My Pictures
----My Videos
---Downloads
----desktop.ini
---Favorites
----desktop.ini
---Music
----desktop.ini
---Pictures
----desktop.ini
---Videos
----desktop.ini
---本目录为用户数据文件,请勿删除
--Windsys_Win10_Pro_1709_X64_V1.5_180226_EasyDrv.wim
--上帝模式.{ED7BA470-8E54-465E-825C-99712043E01C}
-W10系统.rar
-Win7(32位).rar
-Win7(64位).rar

 

posted @ 2019-08-06 12:53  一转身已万水千山  阅读(1962)  评论(0编辑  收藏  举报