Java数据流实现简单的文件分割示例

版权声明:LemonSnm https://blog.csdn.net/LemonSnm/article/details/89857648

文件分割: 

分割一个视频文件,根据文件大小,分割为若干份

package com.lemon;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件分割:
 * 
 * @author lemonSun
 *
 *         2019年5月6日上午9:17:39
 */
public class FileDivisionMergeDemo {

	public static void main(String[] args) {

		// 目标文件
		File file = new File("F:\\javatest\\123.mp4");

		division(file, 1024 * 1024 * 20);// 每个20M,进行分割
	}

	/*
	 * 文件分割 targetFile:要分割的目标文件 cutSize:分割的每个文件大小 每次读取1024
	 */
	private static void division(File targetFile, long cutSize) {

		// 如果文件找不到 return
		if (targetFile == null)
			return;
		// 计算每次读取次数
		int num = targetFile.length() % cutSize == 0 ? (int) (targetFile.length() / cutSize)
				: (int) (targetFile.length() / cutSize + 1);
		try {
			// 字节输入缓冲流
			BufferedInputStream in = new BufferedInputStream(new FileInputStream(targetFile));
			// 字节输出缓冲流
			BufferedOutputStream out = null;
			// 每次读取的字节数
			byte[] bytes = null;
			// 每次实际读取长度
			int len = -1;
			// 每个文件需要读取的次数
			int count = 0;
			// 循环次数 为分割文件的个数
			for (int i = 0; i < num; i++) {
				// 每个输出缓冲流 命名
				out = new BufferedOutputStream(
						new FileOutputStream("F:\\javatest\\" + (i + 1) + "-temp" + targetFile.getName()));
				// 如果分割的大小 小于1024
				if (cutSize < 1024) {
					// 分割的文件 每次读取次数
					bytes = new byte[(int) cutSize];
					count = 1;
				} else {// 如果cutSize大于1024 则每次读取1024
					bytes = new byte[1024];
					count = (int) cutSize / 1024; // 可能有余数
				}
				// 前后顺序不可颠倒 前面的读完20M用完就要跳出循环, 最后一个分割的文件,当输入流文件读完,次数没用完,也要结束
				while (count > 0 && (len = in.read(bytes)) != -1) {
					out.write(bytes, 0, len); // 输出
					out.flush(); // 刷新缓存
					count--; // 次数减一
				}
				// 每个文件大小除以1024的余数 决定是否再读一次
				if (cutSize % 1024 != 0) {
					bytes = new byte[(int) cutSize % 1024];
					len = in.read(bytes);
					out.write(bytes, 0, len);
					out.flush(); // 刷新缓存
					out.close();
				}
			}
			// 全读完了 in关闭
			in.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/*
	 * 文件合并
	 */
	private static void merge() {

	}

}

猜你喜欢

转载自blog.csdn.net/LemonSnm/article/details/89857648