Java字节分割文件流

使用 Java 通过字节分割大文件并将其以文件流的方式读写的示例代码。这个代码展示了如何将一个大文件分割成多个小文件,并以字节流的方式操作文件。

完整代码示例

javascript 复制代码
import java.io.*;

public class FileSplitter {

    public static void main(String[] args) {
        // 原始文件路径
        String sourceFilePath = "largefile.dat";
        // 目标分割文件存放路径
        String targetDirectory = "splitted_files/";
        // 分割文件大小 (单位:字节)
        int splitSize = 1024 * 1024; // 1MB

        try {
            splitFile(sourceFilePath, targetDirectory, splitSize);
            System.out.println("文件分割完成!");
        } catch (IOException e) {
            System.err.println("文件分割失败: " + e.getMessage());
        }
    }

    /**
     * 将大文件按指定大小分割成多个小文件
     * 
     * @param sourceFilePath 原始文件路径
     * @param targetDirectory 分割文件的存放目录
     * @param splitSize 每个分割文件的大小(字节)
     * @throws IOException 文件操作异常
     */
    public static void splitFile(String sourceFilePath, String targetDirectory, int splitSize) throws IOException {
        File sourceFile = new File(sourceFilePath);
        File targetDir = new File(targetDirectory);

        // 如果目标目录不存在,创建目录
        if (!targetDir.exists()) {
            targetDir.mkdirs();
        }

        try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile))) {
            byte[] buffer = new byte[splitSize];
            int bytesRead;
            int partNumber = 1;

            // 按分割大小读取文件并保存为多个小文件
            while ((bytesRead = bis.read(buffer)) > 0) {
                File partFile = new File(targetDirectory + sourceFile.getName() + ".part" + partNumber);
                try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(partFile))) {
                    bos.write(buffer, 0, bytesRead);
                }
                System.out.println("生成分割文件:" + partFile.getName());
                partNumber++;
            }
        }
    }
}

功能描述

输入参数:

原始文件路径(sourceFilePath):需要被分割的大文件的路径。

目标目录路径(targetDirectory):存放分割后的小文件的路径。

分割大小(splitSize):每个小文件的大小(以字节为单位)。

流程:

使用 BufferedInputStream 读取源文件。

按指定大小(splitSize)将文件读取为字节块。

每读取一个字节块,就创建一个新文件(分割文件),并用 BufferedOutputStream 写入。

循环此过程,直到原始文件读取完毕。

输出:

分割后的文件存储在指定的目录下,文件名格式为:原始文件名.part1、原始文件名.part2 等。

重要代码说明

  1. 字节读取与写入
    使用 BufferedInputStream 和 BufferedOutputStream 实现高效的字节流读写操作:
javascript 复制代码
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile))) {
    byte[] buffer = new byte[splitSize];
    int bytesRead;

    while ((bytesRead = bis.read(buffer)) > 0) {
        // 写入分割文件
        try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(partFile))) {
            bos.write(buffer, 0, bytesRead);
        }
    }
}
bis.read(buffer):每次从源文件读取固定大小(splitSize)的字节。
bos.write(buffer, 0, bytesRead):将读取到的字节写入分割文件。
  1. 动态生成分割文件
    每次生成新的文件时,通过动态构建文件名实现:

File partFile = new File(targetDirectory + sourceFile.getName() + ".part" + partNumber);

这将生成文件名类似于:

largefile.dat.part1

largefile.dat.part2

...

3. 目标目录检测与创建

确保目标目录存在,如果不存在则创建:

java 复制代码
if (!targetDir.exists()) {
    targetDir.mkdirs();
}

运行结果

假设:

输入文件为 largefile.dat(大小为 5MB)。

分割大小为 1MB。

运行程序后,将输出以下信息:

生成分割文件:largefile.dat.part1

生成分割文件:largefile.dat.part2

生成分割文件:largefile.dat.part3

生成分割文件:largefile.dat.part4

生成分割文件:largefile.dat.part5

文件分割完成!

目标目录下将生成 5 个分割文件,每个大小约为 1MB。

扩展功能

合并分割文件

反向操作:将分割的文件重新合并为原始文件。

动态文件大小配置

允许用户通过命令行或参数配置分割大小。

多线程分割

为了进一步提升分割速度,可考虑使用多线程同时处理文件分割。

合并文件的示例代码

如果需要将分割的文件合并回原始文件,可以参考以下代码:

java 复制代码
public static void mergeFiles(String targetFilePath, String sourceDirectory) throws IOException {
    File targetFile = new File(targetFilePath);
    File[] partFiles = new File(sourceDirectory).listFiles();

    // 按文件名排序(确保按顺序合并)
    assert partFiles != null;
    Arrays.sort(partFiles, Comparator.comparing(File::getName));

    try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile))) {
        for (File partFile : partFiles) {
            try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(partFile))) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = bis.read(buffer)) > 0) {
                    bos.write(buffer, 0, bytesRead);
                }
            }
            System.out.println("合并文件:" + partFile.getName());
        }
    }
    System.out.println("文件合并完成!");
}

总结

以上代码通过字节流操作实现了文件分割的功能,适用于处理大文件的分片存储与传输需求。这种方式高效且易于扩展,可以满足多种文件操作场景。如果需要更复杂的操作(如多线程处理),可以在此基础上进行优化。

相关推荐
向哆哆5 分钟前
Java 安全:如何防止 DDoS 攻击?
java·安全·ddos
啥都想学的又啥都不会的研究生9 分钟前
Kubernetes in action-初相识
java·docker·微服务·容器·kubernetes·etcd·kubelet
毅航9 分钟前
MyBatis 事务管理:一文掌握Mybatis事务管理核心逻辑
java·后端·mybatis
Chh071518 分钟前
《R语言SCI期刊论文绘图专题计划》大纲
开发语言·r语言
Yeats_Liao20 分钟前
Go 语言 TCP 端口扫描器实现与 Goroutine 池原理
开发语言·tcp/ip·golang
宝耶41 分钟前
面试常问问题:Java基础篇
java·面试·职场和发展
Thomas_YXQ1 小时前
Unity3D IK解算器技术分析
开发语言·搜索引擎·unity·全文检索·unity3d·lucene
躲在云朵里`1 小时前
IDEA搭建环境的五种方式
java·ide·intellij-idea
船长@Quant1 小时前
文档构建:Sphinx全面使用指南 — 基础篇
python·markdown·sphinx·文档构建
喵手1 小时前
从 Java 到 Kotlin:在现有项目中迁移的最佳实践!
java·python·kotlin