天天看點

Java學習筆記之--------IO流之File類的常用方法

File類:檔案和目錄路徑名的抽象表示形式。一個File對象可以代表一個檔案或目錄,但不是完全對應的。建立File對象不會對檔案系統産生影響。(java.io.File)

user.dir:系統根據使用者的工作路徑來解釋相對路徑。

1.檔案名的常用方法

getName():擷取檔案名。

getPath():擷取路徑,如果是絕對路徑,則傳回完整路徑,否則傳回相對路徑。

getAbsolutePath():傳回完整的絕對路徑。

getParent():傳回上級目錄,如果是相對,傳回null。

renameTo(File newName):重命名。

2.判斷資訊

exists():判斷檔案是否存在。

canWrite():判斷檔案是否可寫。

canRead():判斷檔案是否可讀。

isFlie():判斷是否是檔案。

isDirectory():判斷是否是檔案夾。

isAbsolute():消除平台差異,ie以盤符開頭,其他以“/”開頭。

3.長度

length():檔案的位元組數。

4.建立和删除

createNewFile():不存在則建立檔案,存在則傳回false。

delete():删除檔案。

static createTempFlie(字首3個位元組長,字尾預設.temp):預設臨時空間

static createTempFlie(字首3個位元組長,字尾預設.temp,目錄)。

5.操作目錄

mkdir():建立目錄,必須確定父目錄存在,如果不存在則建立失敗。

mkdirs():建立目錄,如果目錄鍊不存在,一同建立。

list():檔案|目錄字元串格式。

listFiles():輸出檔案夾下檔案。

static listRoots():輸出根路徑。

測試類如下:

public class Demo03 {
    public static void main(String[] args) {

        try {
            test03();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("檔案操作失敗!");
        }
    }

    public static void test03() throws IOException{
        String path = "D:/xp/test/200";
        File src = new File(path);
        if (!src.exists()){
            boolean flag = src.createNewFile();
            System.out.println(flag ? "成功" : "失敗");
        }

    }

    public static void test02(){
        String path = "D:/xp/test/2.jpg";
        //String path = "D:/xp/test/200.txt";
        File src = new File(path);
        //是否存在
        System.out.println("檔案是否存在:"+ src.exists());
        //是否可讀
        System.out.println("檔案是否可讀:"+ src.canRead());
        //是否可寫
        System.out.println("檔案是否可寫:"+ src.canWrite());

        System.out.println("檔案的長度為:"+ src.length());

        if (src.isFile()){
            System.out.println("檔案");

        }else if(src.isDirectory()){
            System.out.println("檔案夾");
        }else {
            System.out.println("...");
        }

    }

    public static void test01(){
        File src = new File("2.jpg");
        System.out.println(src.getName());//傳回名稱
        System.out.println(src.getPath());//如果是絕對路徑,傳回完整路徑,否則相對路徑
        System.out.println(src.getAbsolutePath());//傳回絕對路徑
        System.out.println(src.getParent());//傳回上一級目錄,如果是相對路徑,傳回null
    }
}
           

 還有一個實作了輸出子孫級目錄|檔案的名稱功能的代碼:

public class Demo05 {

    public static void main(String[] args) {

        String path = "D:/xp/test";
        File parent = new File(path);
        printName(parent);

        //輸出根路徑:輸出盤符
        File[] roots = File.listRoots();
        System.out.println(Arrays.toString(roots));

    }

    /**
     * 輸出路徑
     */
    public static void printName(File src){
        if (null==src || !src.exists()){
            return;
        }
        System.out.println(src.getAbsolutePath());
        if (src.isDirectory()){
            for (File sub : src.listFiles()){
                printName(sub);
            }
        }
    }
}