DAY21:尚学堂高琪JAVA(164~168)文件分割与合并及IO总结

文件分割

package otherio;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;

//165 文件分割
public class SpiltFile {
	//文件路径
	private String filePath;
	//文件名
	private String fileName;
	//文件大小
	private long length;
	//块数
	private int size;
	//每块大小
	private long blockSize;
	//每块名称
	private List<String> blockPath;
	
	public SpiltFile() {
		blockPath=new ArrayList<String>();
	}
	
	public SpiltFile(String filePath) {
		this(filePath,1024);
	}
	public SpiltFile(String filePath,long blockSize) {
		this();
		this.filePath = filePath;
		this.blockSize=blockSize;
		init();
	}

/*
 * 初始化 计算 块数,确定文件名
 * */


	@SuppressWarnings("null")
	private void init() {
		File src=null;
 
		if (filePath==null||!((src=new File(filePath)).exists())) {
			return;
		}
		this.fileName=src.getName();
		//计算块数 实际大小与每块大小
		this.length=src.length();
		//修正每块的大小
		if (this.blockSize>length) {
			this.blockSize=length;
		}
		//确定块数
		size=(int)(Math.ceil(length*1.0/this.blockSize));
		
	}
		private void initPathName(String destPath){
			for(int i=0;i<size;i++){
				this.blockPath.add(destPath+"/"+this.fileName+"part"+i+".txt");
		}
	}
	/**
	 * 文件分割
	 * 1.第几块
	 * 2.起始位置
	 * 3.实际大小
	 * @param destPath  分割后的文件存放目录
	 * @throws IOException 
	 * */
	public void spilt(String destPath) throws IOException {
		//确定文件路径
		initPathName(destPath);
		long beginPos=0;
		long actualBlockSize=blockSize;
		//计算所有块的索引,大小
		for(int i=0;i<size;i++){
			if (i==size-1) {
				actualBlockSize=this.length-beginPos; 
				
			}
			spiltDetail(i, beginPos, actualBlockSize);
			beginPos=+actualBlockSize;
		}
	}
	/**
	 * @param idex 第几块
	 * @param beginPos 起始点
	 * @param actualBlockSize 实际大小
	 * @throws IOException 
	 * */
	public void spiltDetail(int idex,long beginPos,long actualBlockSize) throws IOException {
		File src=new File(this.filePath);
		File dest=new File(this.blockPath.get(idex));
		
		RandomAccessFile raf1=new RandomAccessFile(src, "r");
		BufferedOutputStream bos1=new BufferedOutputStream(
				new FileOutputStream(dest));
		//读文件
		raf1.seek(beginPos);
		byte[] car=new byte[1024];
		int len=0;
		while(-1!=(len=raf1.read(car))){
			if (actualBlockSize-len>0) {
				bos1.write(car,0,len);
				actualBlockSize-=len;
			}else {
				bos1.write(car,0,(int)actualBlockSize);
				break;
			}
		}
		bos1.close();
		raf1.close();
		
	}
	public static void main(String[] args) throws IOException {
		SpiltFile sf1=new SpiltFile("H:/1/2.txt",50);
		sf1.init();
		System.out.println(sf1.size);
		sf1.spilt("H:/1/11");
	}

}

IO总结

在这里插入图片描述
字节流转字符流:

https://blog.csdn.net/xiaozhu0301/article/details/51593160

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值