java中用文件流分割文件,用于将大文件分割成多个小文件,合并文件待续

该博客介绍了一个Java程序,用于将大文件按指定大小分割成多个小文件。通过`FileSplit`类的`fileSplitMethod`方法,程序利用FileInputStream和FileOutputStream读写文件,确保每个分割文件不超过设定的最大大小。文章没有涉及文件合并部分,但提供了文件命名和保存的逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package test;

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

public class FileSplit {

	private static int nameend = 1;//记录将要在旧名字上加上的编号以生成新文件
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		//File ifile = new File("d:\\test\\iabc.txt");
		//File ifile = new File("d:\\test\\iabc.txt.txt.txt.txt");
		File ifile = new File("d:\\test\\oracle.wmv");
		File ofile = new File("d:\\test");
		FileSplit fs = new FileSplit();
		fs.fileSplitMethod(ifile, ofile, 1024*1024*2);
	}
	
	/**
	 * 
	 * @param ifile 将要分割的文件
	 * @param ofile 将要存放的文件夹
	 * @param filesize 单个文件最大大小byte(字节)
	 * @return 是否分割成功
	 */
	public boolean fileSplitMethod(File	ifile,File ofile,long filesize){
		boolean success = false;
		if(!ifile.exists() || !ifile.isFile() || !ofile.exists() || !ofile.isDirectory() ||  filesize <= 0)
			return success;
		int bufl = 1024; //缓冲字节数组的长度
		if(filesize < bufl)
			bufl = (int) filesize;
		byte[] buf = new byte[bufl];//字节缓冲数组
		int length = 0;//记录当前读取的字节数
		int size = 0;//记录当前文件字节数
		long readsize = 0;
		
		FileInputStream fis = null;
		FileOutputStream fos = null;
		
		try {
			fis = new FileInputStream(ifile);
			fos = new FileOutputStream(getNewFile(ifile,ofile));
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			while((length = fis.read(buf)) != -1){
				fos.write(buf,0,length);
				size += length;
				readsize += length;//记录总已经读取字节数
				if((size + bufl) > filesize && readsize < ifile.length()){//如果再读一个数组会大于最大单个文件大小,并且还有未读字节,则创建新的fos。
					fos.flush();//将缓冲中的写入文件
					fos.close();//关闭这个输出流
					fos = new FileOutputStream(getNewFile(ifile,ofile));//重新创建新的输出流
					size = 0;
				}
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return success;
	}
	
	public File getNewFile(File	ifile,File ofile){
		File file = null;
		String oldname = ifile.getName();//得到旧名字,新名字将在旧名字上加上数字
		String newfilepath = ofile.getPath() + "\\";//用于保存新的file路径
		int endIndex = oldname.lastIndexOf(".");
		if(endIndex > 0){
			String oldnameend = oldname.substring(endIndex, oldname.length());//保存扩展名
			oldname = oldname.substring(0, endIndex);//保存最后一个点左边的名字
			newfilepath += oldname + nameend++ + oldnameend;//新路径
		}else
			newfilepath += oldname + nameend++;
		file = new File(newfilepath);
		return file;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值