1. 程式人生 > >Gorilla帶您學java之File

Gorilla帶您學java之File

檔案

首先是獲取檔案的三種方法

// File類構造方法1 根據絕對路徑或者相對路徑構造
File file = new File("src/dd.txt");

// File類構造方法2 根據 parent 路徑名字串和 child 路徑名字串建立一個新 File 例項。
File file2 = new File("某資料夾名", "wl.txt");

// File類構造方法3 根據 parent 抽象路徑名和 child 路徑名字串建立一個新 File 例項。
File parent = new File("某資料夾名");
File file3 = new File(parent, "wl.txt"
);

下面來來看看File中的一些方法

            // 判斷該路徑是否存在
            boolean b = file.exists();
            System.out.println(b);

            // 獲取絕對路徑的方法
            String absolutePath = file.getAbsolutePath();
            System.out.println(absolutePath);

            // 獲取傳入路徑
            String path = file.getPath();
            System.out.println(path);

            // 判斷方法 
// 判斷一個路徑是否存在 exists(); boolean exists = file.exists(); // 判斷一個路徑是否都是檔案 boolean b2 = file.isFile(); System.out.println(b2); // 判斷一個路徑是否都是資料夾 boolean b3 = parent.isDirectory(); System.out.println(b3); // 建立檔案 注意: 1.該方法只會建立一次 2. 該方法只能建立檔案
boolean b4 = new File("某資料夾名/wll.txt").createNewFile(); System.out.println(b4); // 建立單個資料夾方法 即使帶上檔案字尾 也建立的是資料夾 File file4 = new File("某資料夾名/a.txt"); boolean b5 = file4.mkdir(); System.out.println(b5); // 建立多層級資料夾方法 單層級也能創建出來 File file5 = new File("某資料夾名/b/c"); boolean b6 = file5.mkdirs(); System.out.println(b6); // 刪除檔案(直接刪除 不回去回收站) 1.可以刪除檔案 2.但是隻能刪除空資料夾 boolean b7 = file5.delete(); System.out.println(b7);