zoukankan      html  css  js  c++  java
  • 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.4IdeaProjects
    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
  • 相关阅读:
    URAL 1998 The old Padawan 二分
    URAL 1997 Those are not the droids you're looking for 二分图最大匹配
    URAL 1995 Illegal spices 贪心构造
    URAL 1993 This cheeseburger you don't need 模拟题
    URAL 1992 CVS
    URAL 1991 The battle near the swamp 水题
    Codeforces Beta Round #92 (Div. 1 Only) A. Prime Permutation 暴力
    Codeforces Beta Round #7 D. Palindrome Degree hash
    Codeforces Beta Round #7 C. Line Exgcd
    Codeforces Beta Round #7 B. Memory Manager 模拟题
  • 原文地址:https://www.cnblogs.com/chiweiming/p/11308229.html
Copyright © 2011-2022 走看看