首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java IO 系統入門:從 File 類掌握檔案與目錄操作

     編輯:Java 相關知識

前言:File 類不只是「檔案」

Java IO 體系龐大,但一切的起點是 java.io.File。許多初學者誤以為它僅代表檔案,實則 File 同時代表檔案與目錄,官方文檔稱為「抽象路徑名」。掌握 File 的建構、屬性查詢、目錄遍歷,是後續學習輸入輸出流的基石。

四種建構子,涵蓋所有路徑場景

new File(String pathname)                    // 絕對/相對路徑字串
new File(String parent, String child)        // 父目錄 + 子路徑 (字串)
new File(File parent, String child)          // 父目錄 (File) + 子路徑
new File(URI uri)                            // URI 物件 (如 file:///...)

路徑分隔符注意:Windows 用 \\,Unix/Linux 用 /。建議使用 File.separator 或 Paths.get() (NIO.2) 保證跨平台。

核心操作分類速查

1. 存在性檢查與建立

File dir = new File("hehe");
if (!dir.exists()) dir.mkdir();           // 單層目錄
File sub = new File(dir, "ming/hehe");
if (!sub.exists()) sub.mkdirs();          // 多層目錄 (mkdirs!)

File txt = new File(sub, "ming.txt");
if (!txt.exists()) txt.createNewFile();   // 建立檔案

2. 屬性查詢

file.isFile()         // 是否為檔案
file.isDirectory()    // 是否為目錄
file.getName()        // 檔名/目錄名
file.getParent()      // 父路徑字串
file.getAbsolutePath()// 絕對路徑
file.length()         // 檔案大小 (bytes)
file.lastModified()   // 最後修改時間 (millis)

3. 目錄列舉

// 僅取名稱 (String[])
String[] names = dir.list();  

// 取 File 物件陣列 (可直接遞迴)
File[] files = dir.listFiles();  

// 過濾器範例:只列 .txt
File[] txtFiles = dir.listFiles(f -> f.getName().endsWith(".txt"));

4. 刪除與重命名

file.delete();                    // 刪除 (目錄必須為空)
file.deleteOnExit();              // JVM 退出時刪除 (臨時檔常用)
file.renameTo(new File("new.txt"));// 重命名/移動

完整範例:建立目錄樹並列舉

import java.io.*;

public class FileDemo {
    public static void main(String[] args) throws IOException {
        File root = new File("hehe");
        if (!root.exists()) root.mkdir();

        File branch = new File(root, "ming/hehe");
        if (!branch.exists()) branch.mkdirs();

        // 在分支下建立 1 個主檔 + 5 個編號檔
        File main = new File(branch, "ming.txt");
        if (!main.exists()) main.createNewFile();
        for (int i = 0; i < 5; i++) 
            new File(branch, "ming" + i + ".txt").createNewFile();

        // 列舉
        System.out.println("父路徑: " + branch.getParent());
        for (String name : branch.list()) 
            System.out.println(name);
    }
}

輸出結果

父路徑: hehe\ming
ming.txt
ming0.txt
ming1.txt
ming2.txt
ming3.txt
ming4.txt

進階提示:邁向 NIO.2 (Java 7+)

java.nio.file.Path、Files、FileSystem 提供更豐富、鏈式、異步的 API:

Path p = Paths.get("hehe", "ming", "hehe", "ming.txt");
Files.createDirectories(p.getParent());
Files.writeString(p, "Hello NIO.2");
Stream list = Files.list(p.getParent()); // 串流式處理

總結

  • File 是「路徑抽象」,非資料流,不讀寫內容
  • 掌握 建構 → 存在性 → 屬性 → 列舉 → 刪改 完整生命週期
  • 目錄操作用 mkdirs()、列舉用 listFiles() 配合 Lambda 過濾
  • 新專案優先考慮 java.nio.file,舊代碼維護仍需熟練 File
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved