首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

Java IO 練習:字元流與位元組流實現檔案複製完整範例

     編輯:程式設計綜合問答

實驗目標

分別使用 FileReader/FileWriter(字元流)與 FileInputStream/FileOutputStream(位元組流)實現檔案複製,並比較適用場景。

完整程式碼

package com.test.io;

import java.io.*;

public class JavaIODemo {

    /** 字元流複製(適用文字檔) */
    public boolean copyByChar(File srcFile, File destFile) {
        try (FileReader fr = new FileReader(srcFile);
             FileWriter fw = new FileWriter(destFile)) {
            char[] buff = new char[1024];
            int len;
            while ((len = fr.read(buff)) != -1) {
                fw.write(buff, 0, len);
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    /** 位元組流複製(適用二進位檔:圖片、影片、壓縮檔) */
    public boolean copyByByte(File srcFile, File destFile, int bufferSize) {
        try (FileInputStream fis = new FileInputStream(srcFile);
             FileOutputStream fos = new FileOutputStream(destFile)) {
            byte[] buff = new byte[bufferSize];
            int len;
            while ((len = fis.read(buff)) != -1) {
                fos.write(buff, 0, len);
            }
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }

    public static void main(String[] args) {
        JavaIODemo demo = new JavaIODemo();
        File src = new File("src/com/test/io/JavaIODemo.java");
        File destChar = new File("D:/JavaIODemo_Char.txt");
        File destByte = new File("D:/JavaIODemo_Byte.txt");

        System.out.println("字元流複製:" + (demo.copyByChar(src, destChar) ? "成功" : "失敗"));
        System.out.println("位元組流複製:" + (demo.copyByByte(src, destByte, 1024) ? "成功" : "失敗"));
    }
}

核心差異與選擇指南

特性字元流 (Reader/Writer)位元組流 (InputStream/OutputStream)
處理單位char (2 bytes, UTF-16)byte (1 byte)
編碼轉換自動依平台預設編碼無,原始位元組
適用檔案純文字、XML、JSON、CSV圖片、音訊、視訊、Class、Zip
效能略低(編碼轉換開銷)高,直接記憶體搬移

進階優化

  • 加入 BufferedReader/BufferedWriter 或 BufferedInputStream/BufferedOutputStream 減少系統呼叫次數。
  • JDK 7+ Files.copy(src.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING) 一行搞定,內部採用零拷貝最佳化。
  • 大檔案(>1GB)建議使用 FileChannel.transferTo/transferFrom 實現零拷貝。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved