Java中使用File類創(chuàng)建文件方法總結(jié)
Java 中的 File 類
在 Java 中,文件和文件流是處理數(shù)據(jù)輸入/輸出的兩個(gè)核心概念,它們是 Java I/O 操作的基礎(chǔ)。
一、文件(File)
定義
- 文件是操作系統(tǒng)中的存儲(chǔ)單元,用于持久化保存數(shù)據(jù)(如文本、圖片、二進(jìn)制數(shù)據(jù)等)。
- 在 Java 中,
java.io.File
類(或 Java 7+ 的java.nio.file.Path
)用于表示文件或目錄的抽象路徑。 - 文件本身不存儲(chǔ)數(shù)據(jù),而是通過路徑指向磁盤上的具體數(shù)據(jù)。
二、File 類的介紹
1 創(chuàng)建文件對(duì)象的相關(guān)構(gòu)造器
new File(File parent, String child)
:將父路徑(字符串形式)和子路徑拼接成一個(gè)完整路徑。自動(dòng)處理路徑分隔符(如 Windows 的\
或 Linux 的/
)。// 示例1:拼接父路徑和子文件 String parentDir = "C:/Users/Test"; String childFile = "data.txt"; File file = new File(parentDir, childFile); //會(huì)在2個(gè)目錄之間自動(dòng)加上'/'或'\' System.out.println(file.getPath()); // 輸出: C:\Users\Test\data.txt // 示例2:拼接多級(jí)目錄 File dir = new File("src", "main/java/com/example"); System.out.println(dir.getPath()); // 輸出: src\main\java\com\example
new File(String pathname)
:直接通過路徑名字符串(絕對(duì)路徑或相對(duì)路徑)創(chuàng)建File
對(duì)象。路徑可以是文件或目錄。// 示例1:使用絕對(duì)路徑 File file1 = new File("C:/Users/Test/example.txt"); System.out.println(file1.getPath()); // 輸出: C:\Users\Test\example.txt // 示例2:使用相對(duì)路徑(相對(duì)于當(dāng)前項(xiàng)目根目錄) File file2 = new File("data/config.json"); System.out.println(file2.getPath()); // 輸出: data\config.json
new File(File parent, String child)
:使用一個(gè)已有的File
對(duì)象表示父路徑,再拼接子路徑。比字符串拼接更靈活,避免路徑分隔符錯(cuò)誤。// 示例1:基于父目錄對(duì)象創(chuàng)建子文件 File parentDir = new File("C:/Users/Test"); File childFile = new File(parentDir, "logs/app.log"); System.out.println(childFile.getPath()); // 輸出: C:\Users\Test\logs\app.log // 示例2:鏈?zhǔn)狡唇幽夸? File baseDir = new File("projects"); File srcDir = new File(baseDir, "src"); File mainFile = new File(srcDir, "Main.java"); System.out.println(mainFile.getPath()); // 輸出: projects\src\Main.java
new File(URI rui)
:通過 URI(統(tǒng)一資源標(biāo)識(shí)符) 創(chuàng)建File
對(duì)象。URI 格式需符合file:
協(xié)議(如file:/C:/test/data.txt
)。import java.net.URI; // 示例1:使用URI創(chuàng)建File對(duì)象 try { URI uri = new URI("file:/C:/Users/Test/example.txt"); File file = new File(uri); System.out.println(file.getPath()); // 輸出: C:\Users\Test\example.txt } catch (Exception e) { e.printStackTrace(); } // 示例2:處理空格和特殊字符 //URI 中的特殊字符(如空格)需用 %20 表示,構(gòu)造方法會(huì)解碼后轉(zhuǎn)換為實(shí)際路徑。 URI uri2 = URI.create("file:/C:/My%20Documents/report.pdf"); File file2 = new File(uri2); System.out.println(file2.getPath()); // 輸出: C:\My Documents\report.pdf
總結(jié)對(duì)比
構(gòu)造方法 | 典型使用場(chǎng)景 | 優(yōu)點(diǎn) |
---|---|---|
File(String pathname) | 直接指定完整路徑 | 簡單直接,適合已知路徑 |
File(String parent, String child) | 動(dòng)態(tài)拼接父路徑和子路徑 | 避免手動(dòng)處理路徑分隔符 |
File(File parent, String child) | 基于已有的 File 對(duì)象構(gòu)建子路徑 | 支持鏈?zhǔn)讲僮?,路徑更安?/td> |
File(URI uri) | 從 URI 格式創(chuàng)建(如編碼后的路徑) | 自動(dòng)處理特殊字符和協(xié)議 |
注意 :File 對(duì)象只是一個(gè)路徑的抽象:創(chuàng)建 File 類對(duì)象,并不會(huì)真的在我們電腦上對(duì)應(yīng)的目錄下面創(chuàng)建文件,如果需要實(shí)際的創(chuàng)建文件需要顯式的調(diào)用。
- 構(gòu)造
File
對(duì)象(如new File("a.txt")
)不會(huì)自動(dòng)創(chuàng)建物理文件,僅表示路徑。 - 必須通過顯式調(diào)用 createNewFile() 或其他寫入操作(如
FileOutputStream
寫入數(shù)據(jù))才能實(shí)際生成文件。
2 createNewFile() 的作用
功能:
- 顯式創(chuàng)建一個(gè)空的文件(僅當(dāng)文件不存在時(shí))。
- 如果文件已存在,則返回
false
,不會(huì)覆蓋原有內(nèi)容。
語法:
File file = new File("example.txt"); boolean isCreated = file.createNewFile(); // 返回 true 表示創(chuàng)建成功
- 注意事項(xiàng):
需要處理 IOException:
如果父目錄不存在或沒有寫入權(quán)限,會(huì)拋出異常。
必須用 try-catch 包裹或聲明 throws。
import java.io.File; import java.io.IOException; public class CreateFileDemo { public static void main(String[] args) { File file = new File("test.txt"); try { if (file.createNewFile()) { System.out.println("文件創(chuàng)建成功"); } else { System.out.println("文件已存在"); } } catch (IOException e) { e.printStackTrace(); } } }
父目錄必須存在:
如果路徑中的父目錄不存在,
createNewFile()
會(huì)失敗。需先調(diào)用
file.getParentFile().mkdirs()
創(chuàng)建父目錄:File file = new File("nonexistent_dir/data.txt"); //File 對(duì)象僅表示路徑,不檢查文件是否存在!需通過 exists() 方法驗(yàn)證。 if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); // 創(chuàng)建所有缺失的父目錄 } file.createNewFile();
3 獲取文件相關(guān)信息的常用方法
- getName()
- 作用:返回文件或目錄的名稱(不包含路徑)。
- 示例:路徑為
C:/test/file.txt
時(shí),返回file.txt
;若為目錄C:/test
,返回test
。
- getAbsolutePath()
- 作用:返回文件或目錄的絕對(duì)路徑字符串。
- 注意:無論
File
對(duì)象是相對(duì)路徑還是絕對(duì)路徑創(chuàng)建,均解析為完整路徑。例如,相對(duì)路徑file.txt
可能返回/home/user/file.txt
。
- getParent()
- 作用:返回父目錄的路徑(字符串形式)。若無父目錄(如根目錄或單文件相對(duì)路徑),則返回
null
。 - 示例:路徑為
C:/test/file.txt
時(shí),返回C:/test
;路徑為file.txt
時(shí),返回null
。
- 作用:返回父目錄的路徑(字符串形式)。若無父目錄(如根目錄或單文件相對(duì)路徑),則返回
- length()
- 作用:返回文件的字節(jié)大小。若文件不存在或?yàn)槟夸?,通常返?code>0L。
- 注意:需先通過
exists()
和isFile()
驗(yàn)證目標(biāo)是否為有效文件。
- exists()
- 作用:檢查文件或目錄是否存在,返回布爾值。
- 注意:可能受權(quán)限限制影響(如無訪問權(quán)限時(shí)返回
false
)。
- isFile()
- 作用:判斷是否為標(biāo)準(zhǔn)文件(非目錄或符號(hào)鏈接),返回布爾值。
- 注意:若路徑不存在,返回
false
。
- isDirectory()
- 作用:判斷是否為目錄,返回布爾值。
- 注意:若路徑不存在,返回
false
。
import java.io.File; import java.io.IOException; public class Example { public static void main(String[] args) { read(); } public static void read() { //1.getName() //路徑指向文件 File file1 = new File("D:/0.學(xué)習(xí)/File_Test/read.txt"); System.out.println(file1.getName());// 輸出 read.txt //路徑為目錄 File file2 = new File("D:/0.學(xué)習(xí)/File_Test"); System.out.println(file2.getName());// 輸出 File_Test //2.getAbsolutePath() //以絕對(duì)路徑創(chuàng)建 File 對(duì)象 File file3 = new File("D:/0.學(xué)習(xí)/File_Test/read3.txt"); //輸出 D:/0.學(xué)習(xí)/File_Test/read3.txt System.out.println(file3.getAbsolutePath()); //以相對(duì)路徑創(chuàng)建 File 對(duì)象 File file4 = new File("read4.txt"); //輸出絕對(duì)路徑 D:\0.學(xué)習(xí)\java筆記\java_Code\TankGame\read4.txt System.out.println(file4.getAbsolutePath()); //3.getParent() //File file3 = new File("D:/0.學(xué)習(xí)/File_Test/read3.txt"); //輸出 D:\0.學(xué)習(xí)\File_Test System.out.println(file3.getParent()); //根目錄或單文件相對(duì)路徑,返回 null File file5 = new File("D:"); System.out.println(file5.getParent());//null //4.length() File file6 = new File("D:/0.學(xué)習(xí)/File_Test/read6.txt"); System.out.println(file6.length()); try { file6.createNewFile(); } catch (IOException e) { throw new RuntimeException(e); } System.out.println(file6.length()); } }
4 目錄的操作和文件的刪除
1. mkdir()
- 作用 :創(chuàng)建單層目錄(僅當(dāng)父目錄存在時(shí)才能成功)。
- 返回值 :
boolean
:目錄創(chuàng)建成功返回true
,失敗返回false
。 - 適用場(chǎng)景 :當(dāng)明確知道父目錄已經(jīng)存在時(shí),直接創(chuàng)建子目錄。
2. mkdirs()
- 作用 :創(chuàng)建多層目錄(自動(dòng)創(chuàng)建路徑中所有不存在的父目錄)。
- 返回值 :
boolean
:所有目錄創(chuàng)建成功返回true
,失敗返回false
。 - 適用場(chǎng)景 :不確定父目錄是否存在時(shí),直接創(chuàng)建完整路徑。
3. delete()
- 作用 :刪除文件或空目錄(非空目錄無法刪除)。
- 返回值 :
boolean
:刪除成功返回true
,失敗返回false
。 - 適用場(chǎng)景 :刪除文件或空目錄。
import java.io.File; import java.io.IOException; public class Example { public static void main(String[] args) { dir(); } public static void dir() { //1.mkdir() 創(chuàng)建單層目錄 File file1 = new File("D:/0.學(xué)習(xí)/File_Test/demo1"); //要求父目錄必須存在,否則無法創(chuàng)建成功 //即,D:/0.學(xué)習(xí)/File_Test 必須存在才能成功創(chuàng)建 demo1 目錄 boolean mkdir = file1.mkdir(); if(mkdir) { System.out.println("創(chuàng)建成功"); } else { System.out.println("創(chuàng)建失敗"); } //2.mkdirs() 創(chuàng)建多層目錄 File file2 = new File("D:/0.學(xué)習(xí)/File_Test/demo2"); //如果路徑中有不存在的自動(dòng)創(chuàng)建 boolean mkdirs = file2.mkdirs(); //3.delete() 刪除文件或空目錄(非空目錄無法刪除) //刪除 demo2 空目錄 boolean delete = file2.delete(); File file3 = new File("D:/0.學(xué)習(xí)/File_Test/demo1/dir.txt"); try { file3.createNewFile(); } catch (IOException e) { throw new RuntimeException(e); } //刪除 dir.txt 文件 file3.delete(); } }
總結(jié)
到此這篇關(guān)于Java中使用File類創(chuàng)建文件方法的文章就介紹到這了,更多相關(guān)Java用File類創(chuàng)建文件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java?Zookeeper分布式分片算法超詳細(xì)講解流程
ZooKeeper是一個(gè)分布式的,開放源碼的分布式應(yīng)用程序協(xié)調(diào)服務(wù),是Google的Chubby一個(gè)開源的實(shí)現(xiàn),是Hadoop和Hbase的重要組件。它是一個(gè)為分布式應(yīng)用提供一致性的軟件,提供的功能包括:配置維護(hù)、域名服務(wù)、分布式同步、組服務(wù)等2023-03-03ShardingSphere JDBC強(qiáng)制路由使用的項(xiàng)目實(shí)踐
在某些特定場(chǎng)景下,可能需要繞過分片規(guī)則直接定位到特定的數(shù)據(jù)庫或表,這種情況下就可以使用HintRouting,本文就來介紹一下ShardingSphere JDBC強(qiáng)制路由使用的項(xiàng)目實(shí)踐,感興趣的可以了解一下2024-06-06Springboot整合Mybatis和SQLite的詳細(xì)過程
這篇文章主要介紹了Springboot整合Mybatis和SQLite的詳細(xì)過程,本文通過圖文示例相結(jié)合給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-07-07使用Maven將springboot工程打包成docker鏡像
這篇文章主要介紹了使用Maven將springboot工程打包成docker鏡像,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12Spring事務(wù)處理Transactional,鎖同步和并發(fā)線程
本文詳細(xì)講解了Spring事務(wù)處理Transactional,鎖同步和并發(fā)線程。對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-12-12java實(shí)現(xiàn)統(tǒng)計(jì)字符串中大寫字母,小寫字母及數(shù)字出現(xiàn)次數(shù)的方法示例
這篇文章主要介紹了java實(shí)現(xiàn)統(tǒng)計(jì)字符串中大寫字母,小寫字母及數(shù)字出現(xiàn)次數(shù)的方法,涉及java針對(duì)字符串的遍歷、判斷、運(yùn)算相關(guān)操作技巧,需要的朋友可以參考下2019-06-06Spring-IOC容器-Bean管理-基于XML方式超詳解
這篇文章主要介紹了Spring為IOC容器Bean的管理,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2021-08-08