java文件切割

文件切割既要提供切割功能,又要提供合并功能,下面两个类分别是切割类和合并类,允许用户指定切割尺度,切割后小文件的存放路径以及索引文件。

切割类首先按照用户输入的大小切割成小文件放入指定的文件夹,然后建立索引文件,存放文件个数。

合并类首先读取索引文件,得到原始文件名和小文件个数,然后逐个读取小文件拼接成大文件。

 

切割类:

import java.io.*;
/**
 * 文件分割类
 * @author la
 *
 */
public class CutFile {
	public String fileName=null;
	public long unitSize=0;//每个小文件的大小
	public String targetDir=null;//分割后小文件所在的文件夹
	public int cutFile() throws Exception{
		File file=new File(fileName);
		long size=file.length();//总字节数
		int count=0;//小文件数
		long pos=0;//当前位置
		long last=0;//剩余字节数
		DataInputStream dis=new DataInputStream(new BufferedInputStream(new FileInputStream(file), (int )unitSize));
		byte[] databuf=new byte[(int)unitSize];
		while(pos<size)
		{
			count ++;
			last=size-pos;
			if(last<unitSize)
				databuf=new byte[(int)last];
			dis.read(databuf);
			System.out.println("count="+count+";pos="+pos+";databuf.length="+databuf.length);
			pos=pos+databuf.length;
			//写小文件
			try {
				RandomAccessFile raFile=new RandomAccessFile(targetDir+file.getName()+"_"+count, "rw");
				raFile.write(databuf);
				raFile.close();
			} catch (Exception e) {
				throw e;
			}
		}
		//记载小文件数
		File file1=new File(targetDir+file.getName()+"_count");
		FileWriter fWriter=new FileWriter(file1);
		BufferedWriter bWriter=new BufferedWriter(fWriter);
		String string=(new Integer(count)).toString();
		bWriter.write(string, 0, string.length());
		bWriter.flush();
		bWriter.close();
		return count;
	}
}

合并类:


 

import java.io.*;
/**
 * 文件合并
 * @author la
 *
 */
public class LinkFile {
	public String fileName=null;
	public String targetDir=null;
	public int linkFIle()throws Exception {
		//得到小文件数
		int count=0;
		try {
			File countFile=new File(this.fileName);
			FileReader fReader=new FileReader(countFile);
			BufferedReader bReader=new BufferedReader(fReader);
			bReader.mark(1);
			count=Integer.parseInt(bReader.readLine());
			bReader.close();
		} catch (Exception e) {
			throw e;
		}
		//还原文件名和目录名
		String oldFileName=null;
		String countFileDir=null;
		try {
			String countFileName=new File(this.fileName).getName();
			countFileDir=fileName.substring(0, this.fileName.lastIndexOf(countFileName)).replace('\\', '/');
			oldFileName=countFileName.substring(0, countFileName.length()-6);
		} catch (Exception e) {
			throw e;
		}
		//合并小文件
		FileInputStream fis=null;
		byte[] data=null;
		try {
			FileOutputStream fos=new FileOutputStream(this.targetDir+oldFileName);
			for (int i = 1; i <=count; i++) {
				fis=new FileInputStream(countFileDir+oldFileName+"_"+i);
				data=new byte[fis.available()];
				fis.read(data);
				fis.close();
				fos.write(data);
			}
			fos.close();
		} catch (Exception e) {
			throw e;
		}
		return count;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值