Java檔案操作必備技能,10個小技巧讓你快速掌握!

不一樣的科技宅發表於2023-05-01

前言

  在我們日常的開發中,檔案操作是一個非常重要的主題。檔案讀寫、檔案複製、任意位置讀寫、快取等技巧都是我們必須要掌握的。在這篇文章中,我將給你們介紹 10 個實用的檔案操作技巧。

  1. 使用 try-with-resources 語句處理檔案 IO 流,確保在使用完畢後自動關閉流。
  2. 使用 java.nio.file.Files 類來讀取、寫入和操作檔案。它提供了許多便利的方法,如 copy、move、delete、create 等。
  3. 使用 java.io.File 類操作檔案和目錄,如建立、刪除、重新命名、判斷是否存在等。
  4. 使用 File.separator 來代替硬編碼的檔案路徑分隔符,以保證在不同的作業系統上檔案路徑的正確性。
  5. 使用 FileInputStream 和 FileOutputStream 類來讀寫二進位制檔案,使用 BufferedReader 和 BufferedWriter 類來讀寫文字檔案。
  6. 在讀取大型檔案時,使用 BufferedReader.readLine()方法逐行讀取,而不是一次性讀取整個檔案到記憶體中。
  7. 使用 FileChannel 類進行檔案的快速複製和傳輸,它可以在不使用緩衝區的情況下直接將資料從一個通道傳輸到另一個通道。
  8. 使用 FileReader 和 FileWriter 類讀寫文字檔案時,指定字元編碼方式,以避免出現亂碼問題。
  9. 在處理大型檔案時,使用 RandomAccessFile 類,可以實現對檔案的任意位置讀寫操作。
  10. 對於頻繁讀取的檔案,可以使用快取技術,將檔案資料快取到記憶體中,以提高讀取效率。可以使用 java.io.BufferedInputStream 和 java.io.BufferedOutputStream 類實現快取操作。

示例

1. 使用 try-with-resources 語句處理檔案 IO 流,確保在使用完畢後自動關閉流。

import java.io.*;

public class Example1 {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2. 使用 java.nio.file.Files 類來讀取、寫入和操作檔案。它提供了許多便利的方法,如 copy、move、delete、create 等。

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;

public class Example2 {
    public static void main(String[] args) {
        Path source = Paths.get("file.txt");
        Path target = Paths.get("file_copy.txt");
        try {
            Files.copy(source, target);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. 使用 java.io.File 類操作檔案和目錄,如建立、刪除、重新命名、判斷是否存在等。

import java.io.File;

public class Example3 {
    public static void main(String[] args) {
        File file = new File("file.txt");
        if (file.exists()) {
            System.out.println("File exists!");
        } else {
            System.out.println("File does not exist.");
        }
    }
}

4. 使用 File.separator 來代替硬編碼的檔案路徑分隔符,以保證在不同的作業系統上檔案路徑的正確性。

import java.io.File;

public class Example4 {
    public static void main(String[] args) {
        String path = "C:" + File.separator + "path" + File.separator + "file.txt";
        File file = new File(path);
        System.out.println(file.getAbsolutePath());
    }
}

5. 使用 FileInputStream 和 FileOutputStream 類來讀寫二進位制檔案,使用 BufferedReader 和 BufferedWriter 類來讀寫文字檔案。

import java.io.*;

public class Example5 {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("file.bin");
             FileOutputStream fos = new FileOutputStream("file_copy.bin");
             BufferedInputStream bis = new BufferedInputStream(fis);
             BufferedOutputStream bos = new BufferedOutputStream(fos)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, length);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6. 在讀取大型檔案時,使用 BufferedReader.readLine()方法逐行讀取,而不是一次性讀取整個檔案到記憶體中。

import java.io.*;

public class Example6 {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

7. 使用 FileChannel 類進行檔案的快速複製和傳輸,它可以在不使用緩衝區的情況下直接將資料從一個通道傳輸到另一個通道。

import java.io.*;
import java.nio.channels.FileChannel;

public class Example7 {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("file.txt");
             FileOutputStream fos = new FileOutputStream("file_copy.txt")) {
            FileChannel inChannel = fis.getChannel();
            FileChannel outChannel = fos.getChannel();
            inChannel.transferTo(0, inChannel.size(), outChannel);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

8. 使用 FileReader 和 FileWriter 類讀寫文字檔案時,指定字元編碼方式,以避免出現亂碼問題。

import java.io.*;

public class Example8 {
    public static void main(String[] args) {
        try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("file.txt"), "UTF-8"));
             BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("file_copy.txt"), "UTF-8"))) {
            String line;
            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

9. 在處理大型檔案時,使用 RandomAccessFile 類,可以實現對檔案的任意位置讀寫操作。

import java.io.*;

public class Example9 {
    public static void main(String[] args) {
        try (RandomAccessFile raf = new RandomAccessFile("file.txt", "rw")) {
            raf.seek(raf.length());
            raf.writeBytes("This is a new line.");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

10. 對於頻繁讀取的檔案,可以使用快取技術,將檔案資料快取到記憶體中,以提高讀取效率。可以使用 java.io.BufferedInputStream 和 java.io.BufferedOutputStream 類實現快取操作。

import java.io.*;

public class Example10 {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("file.txt");
             BufferedInputStream bis = new BufferedInputStream(fis)) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = bis.read(buffer)) != -1) {
                // process the data
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

結尾

  如果覺得對你有幫助,可以多多評論,多多點贊哦,也可以到我的主頁看看,說不定有你喜歡的文章,也可以隨手點個關注哦,謝謝。

  我是不一樣的科技宅,每天進步一點點,體驗不一樣的生活。我們下期見!

相關文章