Java File類基礎決議 1
File類的構造方法
public File(String pathname) :通過給定的路徑名字符轉換為抽象路徑名來創建新的File實體
String path = new String("D:\\a.text");
File file = new File(path);
public File(String parent,String child) :從父路徑字串和子路路徑字串來創建新的File實體
String parentpath = new String("D:\\a.text");
String childpath = new String("a.text");
File file = new File(parentpath,childpath);
public File(File parent, String child) :從父抽象路徑名和子路徑名字串創建新的 File實體,
String parentpath = new String("D:\\a");
String childpath=new String("b.text");
File file = new File(parentpath);
File file1 = new File(file, childpath);
System.out.println(file1.getAbsolutePath());
File類常用方法
獲取功能方法
public String getAbsolutePath() :回傳此File的絕對路徑名字串,
public String getPath() :將此File轉換為路徑名字串,
public String getName() :回傳由此File表示的檔案或目錄的名稱,
public long length() :回傳由此File表示的檔案的長度,
代碼演示
package File;
import java.io.File;
public class Main {
public static void main(String[] args) {
String parentpath = new String("D:\\a");
String childpath=new String("b.text");
File file = new File(parentpath,childpath);
System.out.println("獲取絕對路徑:"+file.getAbsolutePath());
System.out.println("獲取構造路徑:"+file.getPath());
System.out.println("獲取檔案名稱:"+file.getName());
System.out.println("獲取檔案長度:"+file.length());
}
}
結果

絕對路徑與相對路徑的區別
絕對路徑:從盤符開始的路徑,這是一個完整的路徑,
相對路徑:相對于專案目錄的路徑,這是一個便捷的路徑,開發中經常使用,
判斷功能的方法
public boolean exists() 此File表示檔案或目錄是否實際存在
public boolean isDirectory():此File表示是否為目錄
public boolean isFile():此File表示的是否為檔案
代碼演示
public class Main {
public static void main(String[] args) {
String parentpath = new String("D:\\test2\\a");
File file = new File(parentpath);
System.out.println("是否為目錄:"+file.isDirectory());
System.out.println("是否為檔案:"+file.isFile());
System.out.println("是否存在:"+file.exists());
}
}
結果

創建洗掉功能的方法
public boolean createNewFile() :當且僅當具有該名稱的檔案尚不存在的時候,創建一個新的空檔案(注意不是檔案夾)
public boolean delete():洗掉由此File表示的目錄或檔案
public boolean mkdir():創建由此File表示的目錄,
public boolean mkdirs():創建由此File表示的目錄,包括任何必須但是不存在的目錄
以上就是javaFile類的一些基礎知識如有錯誤還請各位批評指正,喜歡我的文章的可以關注我,或者點贊收藏

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/141404.html
標籤:Java
上一篇:大資料相關資料論文小結
