1. 程式人生 > 實用技巧 >File建立與刪除

File建立與刪除

package demo01.File;

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

/*
File類建立刪除功能的方法
- public boolean createNewFile() :當且僅當具有該名稱的檔案尚不存在時,建立一個新的空檔案。
- public boolean delete() :刪除由此File表示的檔案或目錄。
- public boolean mkdir() :建立由此File表示的目錄。
- public boolean mkdirs() :建立由此File表示的目錄,包括任何必需但不存在的父目錄。
*/
public class Demo05File {
public static void main(String[] args) throws IOException {
show03();
}

/*
    public boolean delete() :刪除由此File表示的檔案或目錄。
    此方法,可以刪除構造方法路徑中給出的檔案/資料夾
    返回值:布林值
        true:檔案/資料夾刪除成功,返回true
        false:資料夾中有內容,不會刪除返回false;構造方法中路徑不存在false
    注意:
        delete方法是直接在硬碟刪除檔案/資料夾,不走回收站,刪除要謹慎
 */
private static void show03() {
    File f1 = new File("08_FileAndRecursion\\新建資料夾");
    boolean b1 = f1.delete();
    System.out.println("b1:"+b1);

    File f2 = new File("08_FileAndRecursion\\abc.txt");
    System.out.println(f2.delete());
}

/*
   public boolean mkdir() :建立單級空資料夾
   public boolean mkdirs() :既可以建立單級空資料夾,也可以建立多級資料夾
   建立資料夾的路徑和名稱在構造方法中給出(構造方法的引數)
    返回值:布林值
        true:資料夾不存在,建立資料夾,返回true
        false:資料夾存在,不會建立,返回false;構造方法中給出的路徑不存在返回false
    注意:
        1.此方法只能建立資料夾,不能建立檔案
 */
private static void show02() {
    File f1 = new File("08_FileAndRecursion\\aaa");
    boolean b1 = f1.mkdir();
    System.out.println("b1:"+b1);

    File f2 = new File("08_FileAndRecursion\\111\\222\\333\\444");
    boolean b2 = f2.mkdirs();
    System.out.println("b2:"+b2);

    File f3 = new File("08_FileAndRecursion\\abc.txt");
    boolean b3 = f3.mkdirs();//看型別,是一個檔案
    System.out.println("b3:"+b3);

    File f4 = new File("08_F\\ccc");
    boolean b4 = f4.mkdirs();//不會丟擲異常,路徑不存在,不會建立
    System.out.println("b4:"+b4);
}

/*
    public boolean createNewFile() :當且僅當具有該名稱的檔案尚不存在時,建立一個新的空檔案。
    建立檔案的路徑和名稱在構造方法中給出(構造方法的引數)
    返回值:布林值
        true:檔案不存在,建立檔案,返回true
        false:檔案存在,不會建立,返回false
    注意:
        1.此方法只能建立檔案,不能建立資料夾
        2.建立檔案的路徑必須存在,否則會丟擲異常

    public boolean createNewFile() throws IOException
    createNewFile宣告丟擲了IOException,我們呼叫這個方法,就必須的處理這個異常,要麼throws,要麼trycatch
 */
private static void show01() throws IOException {
    File f1 = new File("C:\\Users\\itcast\\IdeaProjects\\shungyuan\\08_FileAndRecursion\\1.txt");
    boolean b1 = f1.createNewFile();
    System.out.println("b1:"+b1);

    File f2 = new File("08_FileAndRecursion\\2.txt");
    System.out.println(f2.createNewFile());

    File f3 = new File("08_FileAndRecursion\\新建資料夾");
    System.out.println(f3.createNewFile());//不要被名稱迷糊,要看型別

    File f4 = new File("08_FileAndRecursi\\3.txt");
    System.out.println(f4.createNewFile());//路徑不存在,丟擲IOException
}

}