--- title: 'Java File 基礎使用' disqus: kyleAlien --- Java File 基礎使用 === ## Overview of Content 如有引用請標明出處 :smile: :::success * 如果喜歡讀更好看一點的網頁版本,可以到我新做的網站 [**DevTech Ascendancy Hub**](https://devtechascendancy.com/) 本篇文章對應的是 [**Java File 操作指南:基礎屬性判斷、資料夾和檔案的創建、以及簡單示範**](https://devtechascendancy.com/java-file-operations-guide/) ::: [TOC] ## Java File * File 是做檔案的基礎處理,可以創建、刪除檔案 & 拿取檔案資料夾的資訊,**但不能讀取檔案內容**,詳細的 API 可以參考 [**極客書 File**](http://tw.gitbook.net/java/io/java_io_file.html),或 [**Java SE 官方網站**](https://docs.oracle.com/javase/7/docs/api/java/io/File.html) | File 常用函數 | 介紹 | | -------- | -------- | | exists() : boolean | 資料夾 or 檔案是否存在 | | createNewFile() : boolean | 創建 **檔案** | | mkdir() : boolean | 創建 **資料夾** | | list() : String[] | 若是已存在的資料夾,則會列出資料夾內的檔案 (資料夾) 名 (**不會遞迴搜尋**),如果是檔案使用,則會返回 Null | | getName() : String | 取得資料名稱 | | length() : long | 資料大小,要用 M 為單位則除 (1024 * 1024) | | isHidden() : boolean | 資料夾是否隱藏 | | lastModified() | 最後更改的時間,這個時間是 Unit Time | ### File 基礎屬性判斷 * 基礎的有 `getName`、`getPath`、`isHidden`、`length` (大小以 **byte 為單位**)、lastModified ... 等等的訊息 ```java= private static void printFile() { File disk = new File("D:\\"); // 找出 D 槽中所有的資料夾 detailFileInfo(disk.listFiles()); } private static void detailFileInfo(File[] files) { if(files == null) { return; } for(File f : files) { if(f.isHidden()) { continue; } System.out.println("File name: " + f.getName() + "\n" + "Path: " + f.getPath() + "\n" + "Length: " + f.length() + "\n" + "Modified: " + f.lastModified() + "\n" // Unit Time ); } } ``` >  ### File 創建 - 資料夾 * 使用 **`mkdir`** 就可以創建資料夾,**若是沒有使用 `exists()` 檢查,創建資料夾則會失敗 (回傳 false)** ```java= private static void createDir(File... files) { for(File f : files) { if(f.exists()) { String[] fileNames = f.list(); // 資料夾內的所有內容 if(fileNames == null) { return; } for (String s : fileNames) { System.out.println(s); } } else { boolean newFile = f.mkdir(); System.out.println("Create dir: " + newFile); } } } ``` ### File 創建 - 檔案 * 使用 File 的函數 **`createNewFile`** 就可以創建檔案,**若是沒有使用 `exists()` 檢查,創建檔案則會失敗 (回傳 false)** ```java= private static void createFile(File... files) throws IOException { for(File f : files) { if(f.exists()) { // 純檔案不需要使用 list() 方法, 如果使用則會返回 null System.out.println("已存在的檔案, 檔案名: " + f.getName()); } else { boolean newFile = f.createNewFile(); System.out.println("Create File: " + newFile); } } } ``` ### File usage Simple Demo * 以下會用 Java File API 創建一個資料夾,並在內部創建一個 myFile.txt 檔案,來演示 Java File API 的基礎簡單使用範例 ```java= public class FiledDemo { public static void main(String[] str) { printFile(); try { makeFile(); } catch (IOException e) { e.printStackTrace(); } } private static void printFile() { File disk = new File("D:\\"); // 找出 D 槽中所有的資料夾 detailFileInfo(disk.listFiles()); } private static void detailFileInfo(File[] files) { if(files == null) { return; } for(File f : files) { if(f.isHidden()) { continue; } System.out.println("File name: " + f.getName() + "\n" + "Path: " + f.getPath() + "\n" + "Length: " + f.length() + "\n" + "Modified: " + f.lastModified() + "\n" // Unit Time ); } } private static void makeFile() throws IOException { File dir = new File("D:\\JavaIO"); File file = new File("D:\\JavaIO\\myFile.txt"); createDir(dir); createFile(file); File[] files = dir.listFiles(); if(files == null) { return; } // 格式轉換 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); for(File childFile : files) { String name = childFile.getName(); // 轉換 Unit Time long mills = childFile.lastModified(); String dateTimeStr =sdf.format(new Date(mills)); System.out.println("File name: " + name + ", Date time: " + dateTimeStr); } } private static void createDir(File... files) { for(File f : files) { if(f.exists()) { String[] fileNames = f.list(); if(fileNames == null) { return; } for (String s : fileNames) { System.out.println("已存在的資料夾, 內部檔案名: " + s); } } else { boolean newFile = f.mkdir(); System.out.println("Create dir: " + newFile); } } } private static void createFile(File... files) throws IOException { for(File f : files) { if(f.exists()) { System.out.println("已存在的檔案, 檔案名: " + f.getName()); } else { boolean newFile = f.createNewFile(); System.out.println("Create File: " + newFile); } } } } ``` 目前的檔案資料層級 (cmd: tree -f) >  **--結果--** >  ## 更多的 Java 語言相關文章 ### Java 語言深入 * 在這個系列中,我們深入探討了 Java 語言的各個方面,從基礎類型到異常處理,從運算子到物件創建與引用細節。點擊連結了解更多! :::info * [**深入探索 Java 基礎類型、編碼、浮點數、參考類型和變數作用域 | 探討細節**](https://devtechascendancy.com/basic-types_encoding_reference_variables-scopes/) * [**深入了解 Java 應用與編譯:從原始檔到命令產出 JavaDoc 文件 | JDK 結構**](https://devtechascendancy.com/java-compilation_jdk_javadoc_jar_guide/) * [**深入理解 Java 異常處理:從基礎概念到最佳實踐指南**](https://devtechascendancy.com/java-jvm-exception-handling-guide/) * [**深入理解 Java 運算子與修飾符 | 重要概念、細節 | equals 比較**](https://devtechascendancy.com/java-operators-modifiers-key-concepts_equals/) * [**深入探索 Java 物件創建與引用細節:Clone 和finalize 特性,以及強、軟、弱、虛引用**](https://devtechascendancy.com/java-object-creation_jvm-reference-details/) ::: ### Java IO 相關文章 * 探索 Java IO 的奧秘,了解檔案操作、流處理、NIO等精彩內容! :::warning * [**Java File 操作指南:基礎屬性判斷、資料夾和檔案的創建、以及簡單示範**](https://devtechascendancy.com/java-file-operations-guide/) * [**深入探索 Java 編碼知識**](https://devtechascendancy.com/basic-types_encoding_reference_variables-scopes/) * [**深入理解 Java IO 操作:徹底了解流、讀寫、序列化與技巧**](https://devtechascendancy.com/deep-in-java-io-operations_stream-io/) * [**深入理解 Java NIO:緩衝、通道與編碼 | Buffer、Channel、Charset**](https://devtechascendancy.com/deep-dive-into-java-nio_buf-channel-charset/) ::: ### 深入 Java 物件導向 * 探索 Java 物件導向的奧妙,掌握介面、抽象類、繼承等重要概念! :::danger * [**深入比較介面與抽象類:從多個角度剖析**](https://devtechascendancy.com/comparing-interfaces-abstract-classes/) * [**深度探究物件導向:繼承的利與弊 | Java、Kotlin 為例 | 最佳實踐 | 內部類細節**](https://devtechascendancy.com/deep-dive-into-oop-inheritance/) * [**「類」的生命週期、ClassLoader 加載 | JVM 與 Class | Java 為例**](https://devtechascendancy.com/class-lifecycle_classloader-exploration_jvm/) ::: ## Appendix & FAQ :::info ::: ###### tags: `Java 基礎`
×
Sign in
Email
Password
Forgot password
or
Sign in via Google
Sign in via Facebook
Sign in via X(Twitter)
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
Continue with a different method
New to HackMD?
Sign up
By signing in, you agree to our
terms of service
.