Java文件分片与合并

Posted 向天再借500年V

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java文件分片与合并相关的知识,希望对你有一定的参考价值。

Java文件分片与合并


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
 
public class FileSpiltAndMerge 
 
	public static void main(String[] args) throws IOException 
		spilt("D:\\\\0000\\\\www.mp4", 1, "D:\\\\0000\\\\wc");
		merge("D:\\\\0000\\\\wc", "D:\\\\0000\\\\hebing.mp4");
	
 
	public static void spilt(String from, int size, String to) throws IOException 
		File f = new File(from);
		FileInputStream in = new FileInputStream(f);
		FileOutputStream out = null;
		FileChannel inChannel = in.getChannel();
		FileChannel outChannel = null;
 
		// 将MB单位转为为字节B
		long m = size * 1024 * 1024;
		// 计算最终会分成几个文件
		int count = (int) (f.length() / m);
		for (int i = 0; i <= count; i++) 
			// 生成文件的路径
			String t = to + "/" + i;
			try 
				out = new FileOutputStream(new File(t));
				outChannel = out.getChannel();
				// 从inChannel的m*i处,读取固定长度的数据,写入outChannel
				if (i != count)
					inChannel.transferTo(m * i, m, outChannel);
				else// 最后一个文件,大小不固定,所以需要重新计算长度
					inChannel.transferTo(m * i, f.length() - m * count, outChannel);
			 catch (IOException e) 
				e.printStackTrace();
			 finally 
				out.close();
				outChannel.close();
			
		
		in.close();
		inChannel.close();
	
 
	public static void merge(String from, String to) throws IOException 
		File t = new File(to);
		FileInputStream in = null;
		FileChannel inChannel = null;
 
		FileOutputStream out = new FileOutputStream(t, true);
		FileChannel outChannel = out.getChannel();
 
		File f = new File(from);
		// 获取目录下的每一个文件名,再将每个文件一次写入目标文件
		if (f.isDirectory()) 
			List<File> list = getAllFileAndSort(from);
			// 记录新文件最后一个数据的位置
			long start = 0;
			for (File file : list) 
 
				in = new FileInputStream(file);
				inChannel = in.getChannel();
 
				// 从inChannel中读取file.length()长度的数据,写入outChannel的start处
				outChannel.transferFrom(inChannel, start, file.length());
				start += file.length();
				in.close();
				inChannel.close();
			
		
		out.close();
		outChannel.close();
	
	
	private static List<File> getAllFileAndSort(String dirPath) 
		File dirFile = new File(dirPath);
		File[] listFiles = dirFile.listFiles();
		List<File> list = Arrays.asList(listFiles);
		Collections.sort(list, (o1, o2) -> 
			return Integer.parseInt(o1.getName()) - Integer.parseInt(o2.getName());
		);
		return list;
	


以上是关于Java文件分片与合并的主要内容,如果未能解决你的问题,请参考以下文章

大文件上传前台分片后后台合并的问题

进行大文件的分片操作(split),合并(cat/copy)

ElasticSearch探索之路集群与分片:选举动态更新近实时搜索事务日志段合并

ElasticSearch探索之路集群与分片:选举动态更新近实时搜索事务日志段合并

ElasticSearch探索之路集群与分片:选举动态更新近实时搜索事务日志段合并

基于ffmpeg下载.ts流媒体分片传输文件自动合并单独完整mp4文件,windows