怎么在java中使用IO流将一个文件拆分为多个子文件

这篇文章将为大家详细讲解有关怎么在java中使用IO流将一个文件拆分为多个子文件,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

基本思路:

怎么在java中使用IO流将一个文件拆分为多个子文件

如果有一个大文件,指定分割大小后(比如:按1M切割)

step 1:

先根据原始文件大小、分割大小,算出最终分割的小文件数N

step 2:

在磁盘上创建这N个小文件

step 3:

开多个线程(线程数=分割文件数),每个线程里,利用RandomAccessFile的seek功能,将读取指针定位到原文件里每一段的段首位置,然后向后读取指定大小(即:分割块大小),最终写入对应的分割文件,因为多线程并行处理,各写各的小文件,速度相对还是比较快的。

下面代码是将一个文件拆分为多个子文件,每个大小是100K

package testIO;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Arrays;
public class subStream {
	public static void main(String[] args) {
		//先将源文件读取到内存中 
		int eachSize=100*1024;
		File srcFile =new File("F:/test/test.txt");
		//创建一个文件对象 
		splitFile(srcFile,eachSize);
	}
	public static void splitFile(File srcFile,int eachSize){
		//判断文件是否符合拆分要求 
		if(srcFile.length()==0){
			throw new RuntimeException("文件不符合拆分要求");
		}
		byte[] fileContent= new byte[(int) srcFile.length()];
		try {
			//将文件内容读取到内存中 
			FileInputStream fis=new FileInputStream(srcFile);
			fis.read(fileContent);
			fis.close();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		//计算要次要拆分为多少份 
		int fileNumber;
		if(fileContent.length%eachSize==0){
			fileNumber = fileContent.length/eachSize;
		} else{
			fileNumber = fileContent.length/eachSize+1;
		}
		for (int i=0;i<fileNumber;i++){
			String fileName = srcFile.getName()+"-"+i+".txt";
			File fi = new File(srcFile.getParent(), fileName);
			//在当前文件路径下创建拆分的文件 
			byte[] eachContent;
			//将源文件内容复制到拆分的文件中 
			if(i!=fileNumber-1){
				eachContent = Arrays.copyOfRange(fileContent, eachSize*i, eachSize*(i+1));
			} else{
				eachContent = Arrays.copyOfRange(fileContent, eachSize*i, fileContent.length);
			}
			try {
				FileOutputStream fos = new FileOutputStream(fi);
				fos.write(eachContent);
				fos.close();
				System.out.printf("输出子文件 %s,其大小是 %d,每个的大小是%d\n",fi.getAbsoluteFile(),fi.length(),eachContent.length);
			}
			catch (Exception e) {
				// TODO: handle exception 
				e.printStackTrace();
			}
		}
	}
}

关于怎么在java中使用IO流将一个文件拆分为多个子文件就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。