Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Java 檔案拷貝三種寫法:從逐位元組到緩衝串流

Java 的串流(Stream)是基礎中的基礎,檔案讀寫與拷貝更是面試常見考點。本文用同一個需求、三種實作做對照,順便量一下差異。

文本 IO 與二進位 IO

先記住一組對照:字元層級用 Reader/Writer(搭配 BufferedReader/BufferedWriter 提升效能),位元組層級用 InputStream/OutputStream(搭配 BufferedInputStream/BufferedOutputStream)。拷貝任意檔案時應走位元組流,才能避免編碼問題。

寫法一:逐位元組讀寫

package com.gdufe.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class TestInputOutputStream {

    private final static String SOURCE = "D:\\Tool_Software\\mysql-installer-community-5.6.23.0.msi";
    private final static String TARGET = "mysql-installer-community-5.6.23.0.msi";

    public static void main(String[] args) {
        TestInputOutputStream.copy1(SOURCE, TARGET);
        System.out.println("--End---");
    }

    public static void copy1(String src, String tar) {
        InputStream input = null;
        OutputStream output = null;
        try {
            input = new FileInputStream(src);
            output = new FileOutputStream(tar);
            int r;
            while ((r = input.read()) != -1) {
                output.write((byte) r);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                input.close();
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

每次只搬一個位元組,功能正確但速度最差——每個位元組都是一次系統呼叫。

寫法二:以位元組陣列為單位

public static void copy2(String src, String tar) {
    InputStream input = null;
    OutputStream output = null;
    try {
        input = new FileInputStream(src);
        output = new FileOutputStream(tar);
        int length = 0;
        byte[] b = new byte[1024];
        while ((length = input.read(b)) != -1) {
            output.write(b, 0, length);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            input.close();
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

一次搬 1KB,速度立刻改善一個量級。注意 write 的第三個參數必須是 length 而不是 b.length,否則最後一筆不足 1KB 時會寫入多餘的垃圾位元組。

寫法三:加上緩衝串流

public static void copy3(String src, String tar) {
    InputStream input = null;
    OutputStream output = null;
    try {
        input = new DataInputStream(new BufferedInputStream(new FileInputStream(src)));
        output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(tar)));

        int length = 0;
        byte[] b = new byte[1024];   // 先將資料讀入位元組陣列
        while ((length = input.read(b)) != -1) {
            output.write(b, 0, length);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            input.close();   // 關閉最外層即可,內層會一併關閉
            output.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

實測加了 buffer 的版本確實更快,因為它大幅降低了實際的系統呼叫次數。

兩個實務提醒

  • 測試前請確認來源檔案存在,否則會拿到 FileNotFoundException(訊息看起來就像「file can't be found」);拷貝到 Java 專案目錄後記得 refresh 才看得到。
  • Java 7 之後可以直接用 NIO.2 一行解決,並自動處理串流關閉:
Files.copy(Paths.get(src), Paths.get(tar), StandardCopyOption.REPLACE_EXISTING);

另外,若來源與目標相同,自拷貝會出錯誤;需要「邊讀邊寫」時也應改用 FileChannel 的 transferTo,避免自己覆蓋自己。

Copyright © Linux教程網 All Rights Reserved