Java字节流案例怎么读写文件

wen java案例 22

本文目录导读:

Java字节流案例怎么读写文件

  1. 基本字节流读写文件
  2. 实际应用案例
  3. 实用工具类
  4. 关键知识点总结

我来为你介绍Java字节流读写文件的完整案例。

基本字节流读写文件

使用FileInputStream和FileOutputStream

import java.io.*;
public class ByteStreamExample {
    public static void main(String[] args) {
        // 1. 逐字节读写(不推荐用于大文件)
        readWriteByteByByte();
        // 2. 使用缓冲区读写(推荐方式)
        readWriteWithBuffer();
        // 3. 使用try-with-resources自动关闭资源
        readWriteWithTryResources();
    }
    // 方法1:逐字节读写
    public static void readWriteByteByByte() {
        FileInputStream fis = null;
        FileOutputStream fos = null;
        try {
            fis = new FileInputStream("source.txt");
            fos = new FileOutputStream("destination.txt");
            int byteData;
            while ((byteData = fis.read()) != -1) {
                fos.write(byteData);
            }
            System.out.println("文件复制完成(逐字节方式)");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (fis != null) fis.close();
                if (fos != null) fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    // 方法2:使用缓冲区读写(推荐)
    public static void readWriteWithBuffer() {
        try {
            FileInputStream fis = new FileInputStream("source.txt");
            FileOutputStream fos = new FileOutputStream("destination.txt");
            byte[] buffer = new byte[1024]; // 1KB缓冲区
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            fis.close();
            fos.close();
            System.out.println("文件复制完成(缓冲区方式)");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 方法3:使用try-with-resources(Java 7+)
    public static void readWriteWithTryResources() {
        // 自动关闭资源
        try (FileInputStream fis = new FileInputStream("source.txt");
             FileOutputStream fos = new FileOutputStream("destination.txt")) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            System.out.println("文件复制完成(try-with-resources方式)");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

实际应用案例

案例1:复制图片文件

import java.io.*;
public class ImageCopyExample {
    public static void copyImage(String sourcePath, String destPath) {
        try (FileInputStream fis = new FileInputStream(sourcePath);
             FileOutputStream fos = new FileOutputStream(destPath)) {
            byte[] buffer = new byte[8192]; // 8KB缓冲区
            int bytesRead;
            long startTime = System.currentTimeMillis();
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            long endTime = System.currentTimeMillis();
            System.out.println("图片复制完成!耗时:" + (endTime - startTime) + "ms");
        } catch (IOException e) {
            System.err.println("文件复制失败: " + e.getMessage());
        }
    }
    public static void main(String[] args) {
        copyImage("C:/photos/photo.jpg", "D:/backup/photo_copy.jpg");
    }
}

案例2:文件加密(简单异或加密)

import java.io.*;
public class FileEncryptExample {
    // 简单异或加密
    public static void encryptFile(String source, String dest, byte key) {
        try (FileInputStream fis = new FileInputStream(source);
             FileOutputStream fos = new FileOutputStream(dest)) {
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                // 对每个字节进行异或加密
                for (int i = 0; i < bytesRead; i++) {
                    buffer[i] ^= key;
                }
                fos.write(buffer, 0, bytesRead);
            }
            System.out.println("文件加密完成");
        } catch (IOException e) {
            System.err.println("加密失败: " + e.getMessage());
        }
    }
    // 解密(异或两次即可解密)
    public static void decryptFile(String source, String dest, byte key) {
        encryptFile(source, dest, key); // 相同的异或操作即可解密
    }
    public static void main(String[] args) {
        // 加密文件
        encryptFile("original.txt", "encrypted.txt", (byte) 0x7F);
        // 解密文件
        decryptFile("encrypted.txt", "decrypted.txt", (byte) 0x7F);
    }
}

案例3:大文件分块复制

import java.io.*;
public class LargeFileCopyExample {
    // 分块复制,显示进度
    public static void copyWithProgress(String source, String dest) throws IOException {
        File sourceFile = new File(source);
        long fileSize = sourceFile.length();
        try (FileInputStream fis = new FileInputStream(sourceFile);
             FileOutputStream fos = new FileOutputStream(dest)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            long totalBytesRead = 0;
            int progressPercent = 0;
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
                totalBytesRead += bytesRead;
                // 计算并显示进度
                int newProgress = (int) (totalBytesRead * 100 / fileSize);
                if (newProgress > progressPercent) {
                    progressPercent = newProgress;
                    System.out.print("\r复制进度: " + progressPercent + "%");
                }
            }
            System.out.println("\n文件复制完成!");
        } catch (IOException e) {
            throw new IOException("文件复制失败", e);
        }
    }
    public static void main(String[] args) {
        try {
            copyWithProgress("largefile.bin", "largefile_copy.bin");
        } catch (IOException e) {
            System.err.println("错误: " + e.getMessage());
        }
    }
}

实用工具类

import java.io.*;
public class FileUtil {
    // 复制文件
    public static void copyFile(String source, String dest) throws IOException {
        try (FileInputStream fis = new FileInputStream(source);
             FileOutputStream fos = new FileOutputStream(dest)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
        }
    }
    // 读取文件到字节数组
    public static byte[] readFileToBytes(String filePath) throws IOException {
        File file = new File(filePath);
        byte[] data = new byte[(int) file.length()];
        try (FileInputStream fis = new FileInputStream(file)) {
            fis.read(data);
        }
        return data;
    }
    // 写入字节数组到文件
    public static void writeBytesToFile(byte[] data, String filePath) throws IOException {
        try (FileOutputStream fos = new FileOutputStream(filePath)) {
            fos.write(data);
        }
    }
    // 获取文件大小
    public static long getFileSize(String filePath) {
        File file = new File(filePath);
        return file.exists() ? file.length() : -1;
    }
}
// 使用示例
public class FileUtilDemo {
    public static void main(String[] args) {
        try {
            // 复制文件
            FileUtil.copyFile("source.txt", "dest.txt");
            // 读取文件
            byte[] fileData = FileUtil.readFileToBytes("config.bin");
            System.out.println("文件大小: " + fileData.length + " 字节");
            // 写入文件
            String content = "Hello, World!";
            FileUtil.writeBytesToFile(content.getBytes(), "output.txt");
        } catch (IOException e) {
            System.err.println("操作失败: " + e.getMessage());
        }
    }
}

关键知识点总结

  1. 缓冲区的选择:一般使用1KB-8KB的缓冲区
  2. 资源管理:使用try-with-resources自动关闭资源
  3. 异常处理:正确处理IOException
  4. 性能优化:使用缓冲区而不是逐字节读写
  5. 文件路径:注意使用正确的文件路径分隔符

这些案例涵盖了Java字节流的基本用法和实际应用场景,可以根据具体需求选择合适的实现方式。

抱歉,评论功能暂时关闭!