首頁  >  文章  >  Java  >  Java 檔案操作入門指南:從零到精通

Java 檔案操作入門指南:從零到精通

PHPz
PHPz轉載
2024-02-27 21:49:02645瀏覽

Java 文件操作入门指南:从零到精通

一、檔案操作基礎

  1. 建立檔案

建立檔案可以使用 java.<strong class="keylink">io</strong>.File 類別的 createNewFile() 方法。如果檔案已經存在,則該方法會拋出 IOException 例外。

File file = new File("myfile.txt");
file.createNewFile();
  1. 讀取檔案

讀取檔案可以使用 java.io.FileReader 類別。類別提供了 read()readLine() 方法來讀取檔案內容。

FileReader reader = new FileReader("myfile.txt");
BufferedReader bufferedReader = new BufferedReader(reader);

String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}

bufferedReader.close();
  1. 寫入檔案

寫入檔案可以使用 java.io.FileWriter 類別。類別提供了 write()writeLines() 方法來寫入檔案內容。

FileWriter writer = new FileWriter("myfile.txt");
BufferedWriter bufferedWriter = new BufferedWriter(writer);

bufferedWriter.write("Hello, world!");
bufferedWriter.newLine();
bufferedWriter.write("This is a new line.");

bufferedWriter.close();
  1. 複製檔案

複製檔案可以使用 java.<strong class="keylink">NIO</strong>.file.Files 類別的 copy() 方法。該方法將來源檔案複製到目標檔案。

Files.copy(Paths.get("myfile.txt"), Paths.get("myfile_copy.txt"));
  1. 移動檔案

移動檔案可以使用 java.nio.file.Files 類別的 move() 方法。該方法將來源檔案移至目標檔案。

Files.move(Paths.get("myfile.txt"), Paths.get("new_folder/myfile.txt"));
  1. 刪除檔案

刪除檔案可以使用 java.io.File 類別的 delete() 方法。如果檔案不存在,則該方法會傳回 false

File file = new File("myfile.txt");
file.delete();

二、進階檔案操作

  1. #檔案鎖定

檔案鎖定可以防止多個進程同時存取同一個檔案。 Java 中可以使用 java.nio.channels.FileLock 類別來加鎖檔案。

FileChannel channel = FileChannel.open(Paths.get("myfile.txt"), StandardOpenOption.WRITE);
FileLock lock = channel.lock();

// 对文件进行操作

lock.release();
  1. 檔案元資料

檔案元資料包含檔案的屬性,如檔案大小、建立時間、修改時間等。 Java 中可以使用 java.nio.file.Files 類別的 getAttribute()setAttribute() 方法來取得和設定檔案元資料。

Map<String, Object> attrs = Files.getAttribute(Paths.get("myfile.txt"), "basic");
System.out.println(attrs.get("size"));
System.out.println(attrs.get("creationTime"));
System.out.println(attrs.get("lastModifiedTime"));

Files.setAttribute(Paths.get("myfile.txt"), "creationTime", new FileTime(Instant.now()));
  1. Java NIO

Java NIO(New Input/Output)是 Java 7 中引入的新 I/O api,它提供了更快的 I/O 效能。 Java NIO 使用非阻塞 I/O,這意味著它可以在不等待 I/O 作業完成的情況下繼續執行其他任務。

Java NIO 中最常用的類別是 java.nio.channels.FileChannel。類別提供了 read()write() 方法來讀取和寫入檔案。

FileChannel channel = FileChannel.open(Paths.get("myfile.txt"), StandardOpenOption.READ);

ByteBuffer buffer = ByteBuffer.allocate(1024);
while (channel.read(buffer) > 0) {
buffer.flip();
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
buffer.clear();
}

channel.close();

總結

Java 檔案操作是 Java 程式設計中的基本知識,也是許多應用的基礎。本文介紹了Java 檔案操作的基本知識,從建立、讀取、寫入、複製、移動和刪除檔案開始,到進階操作,如檔案鎖定和元資料操作,以及如何使用檔案操作庫(如Java NIO)來提高性能。希望本文能幫助讀者更能理解並使用 Java 檔案操作。

>軟考高級考試備考技巧/歷年真題/備考精華資料" target="_blank">點擊免費下載>>軟考高級考試備考技巧/歷年真題/備考精華資料

以上是Java 檔案操作入門指南:從零到精通的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:lsjlt.com。如有侵權,請聯絡admin@php.cn刪除