文件分割
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.youkuaiyun.com/xiaozhu0301/article/details/51593160