文件切割者RandomAccessFile
public class TestIOS{
public static void main(String [] args){
// src需要切割的文件路径
String src="src/com/sxt/test/TestIOS.java";
RandTest1(src);
}
/**
* 文件分割
*/
public static void RandTest1(String src){
//获取数据源
File file=new File(src);
//获取文件的总长度
long len = file.length();
System.out.println(len);
//获取文件一次性读取的大小
int size=2048;
//文件的总块数 四舍五入取整
int kuaishu = (int) Math.ceil((len*1.0)/size);
System.out.println(kuaishu);
//初始长度
int start=0;
//实际长度=固定长度>总长度?说明文件已经读到最后一块(读取剩余长度):文件没有读到最后一块(读取固定长度)
int actualSize= size>len? (int) len :size;
//通过块数进行遍历
for(int i=0;i<kuaishu;i++){
//不断地更新初始长度
start=i*size;
//如果固定块数为最后一块 实际长度就等于剩余长度值
if (i==kuaishu-1){
actualSize= (int) len;
}else{
//否则的话就是 没有到最后一块 实际长度等于固定长度
actualSize=size;
//将已经用过的长度值减掉
len-=actualSize;
}
//调用读取文件的方法
RandTest(i,start,actualSize,src);
System.out.println();
System.out.println();
System.out.println("块数:"+i+"---------初始值:"+start+"-----------实际大小:"+actualSize);
System.out.println();
System.out.println();
}
}
/**
* 形参意思如下:
* 第几块 起始位置 实际大小 文件路径
* 分段截取指定的数据,文件分割
*/
public static void RandTest(int i,int startPro,int actualSize,String src){
//文件分割
RandomAccessFile raf=null;
try {
raf = new RandomAccessFile(src,"r");
//***从起始位置索引处开始进行获取数据
raf.seek(startPro);
//创建字节数组做为缓冲区
byte[] flash = new byte[2048];
//声明一个整形变量,用来获取文件读取的长度
int len=-1;
//循环读取文件 直到文件读取结束.len=-1;
while ((len=raf.read(flash))!=-1){
//如果本次读取的内容长度>=上次读取的长度 则继续读
if (actualSize>=len){
System.out.println(new String(flash,0,len));
actualSize-=len; //下次实际要读的容量=固定容量-已读容量
}else{
System.out.println(new String(flash,0,actualSize));//读取剩余的数据,之后跳出循环
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}