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

Java File 類別操作檔案與目錄完整指南

     編輯:Java 相關知識

前言

java.io.File 類別是 Java 操作檔案系統的入口,雖不直接處理檔案內容,但提供建立、刪除、重命名、屬性查詢、目錄列舉等豐富功能。本文系統整理其核心用法。

建立 File 物件的三種方式

// 1. 直接給路徑字串
File myFile = new File("etc/motd");

// 2. 目錄與檔名分開(適合變數組合)
myFile = new File("/etc", "motd");

// 3. 先建立目錄物件再建立檔案物件
File myDir = new File("/etc");
myFile = new File(myDir, "motd");

情境選擇:單一檔案用方式 1;同目錄多檔案用方式 2 或 3。

常用方法分類速查

1. 檔案名稱與路徑

  • getName():檔案名稱
  • getPath():相對路徑
  • getAbsolutePath():絕對路徑
  • getParent():父目錄路徑
  • renameTo(File newName):重命名/移動

2. 檔案測試

  • exists():是否存在
  • canRead()、canWrite():讀寫權限
  • isFile()、isDirectory():類型判斷
  • isAbsolute():是否為絕對路徑

3. 一般檔案資訊

  • lastModified():最後修改時間(毫秒時間戳)
  • length():檔案大小(位元組)

4. 目錄操作

  • mkdir():建立目錄(單層)
  • mkdirs():建立多層目錄(JDK 1.2+)
  • list():列出檔名陣列
  • listFiles():列出 File 物件陣列(JDK 1.2+)

完整範例:命令列檔案資訊查看器

import java.io.*;

public class FileInfo {
    public static void main(String[] args) throws IOException {
        if (args.length > 0) {
            for (int i = 0; i < args.length; i++) {
                File fileToCheck = new File(args[i]);
                printInfo(fileToCheck);
            }
        } else {
            System.out.println("No file given.");
        }
    }

    static void printInfo(File f) throws IOException {
        System.out.println("Name: " + f.getName());
        System.out.println("Path: " + f.getPath());
        if (f.exists()) {
            System.out.println("File exists.");
            System.out.print(f.canRead() ? " and is Readable" : "");
            System.out.print(f.canWrite() ? " and is Writeable" : "");
            System.out.println(".");
            System.out.println("File is " + f.length() + " bytes.");
        } else {
            System.out.println("File does not exist.");
        }
    }
}

執行方式

javac FileInfo.java
java FileInfo /etc/passwd /tmp/test.txt

進階提示

  • 路徑分隔符:Windows 用 \\,Unix/Linux 用 /。可用 File.separator 取得平台相關分隔符。
  • 臨時檔案:File.createTempFile(prefix, suffix, dir) 可建立唯一臨時檔。
  • 刪除掛鉤:file.deleteOnExit() 讓 JVM 結束時自動刪除。
  • Java 7+ NIO.2:新專案建議改用 java.nio.file.Path、Files、FileSystem 等更強大的 API。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved