* 作用:RandomAccessFile综合练习
*
*@author hby_gd@163.com
*@date 2/6/2020 下午9:04
*/
import java.io.*;
import java.util.ArrayList;
import java.util.List;
/**
* 文件的分割
* 1、属性:源文件路径、大小,目标文件所在目录、大小、个数、名字
* 2、分割 每次循环,确定分割的起点和终点
*/
public class SplitFile {
private String sourcePath;
private long length;
//给定默认输出目录
private String endPath = "D:/test/words";
private long size;
private int nums;
private List<String> nameList;
public int getNums(){return nums;}
public long getLength(){return length;}
public long getSize(){return size;}
public SplitFile() {
nameList = new ArrayList<String>();
}
public SplitFile(String sourcePath,long size){
this();
this.sourcePath = sourcePath;
this.size = size;
init();
}
public SplitFile(String sourcePath){
this(sourcePath,10l);
}
/**
* 初始化,将其他属性赋值
*/
private void init(){
File file = new File(sourcePath);
//判断源文件是否合法
if(null==sourcePath||!file.exists()||file.isDirectory()){
System.out.println("目标文件不存在或有误");
return;
}
this.length = file.length();
this.nums = (int)(Math.ceil(((double)length)/size));
for (int i = 0; i < nums; i++) {
nameList.add("文件"+i+".txt");
}
}
/**
* 文件分割
*/
public void split() throws IOException {
long startPoint = 0;
for (int i = 0; i < nums; i++) {
if(i==nums-1){
splitDetail(i,startPoint,length-startPoint);
return;
}
splitDetail(i,startPoint,size);
startPoint+=size;
}
}
//单个分割实现
public void splitDetail(int i,long startpoint,long endpoint) throws IOException {
File file = new File(endPath,nameList.get(i));
OutputStream ops = new BufferedOutputStream(new FileOutputStream(file));
File sourceFile = new File(sourcePath);
RandomAccessFile rdf = new RandomAccessFile(sourceFile,"r");
rdf.seek(startpoint);
byte[] flush = new byte[1024];
int len = 0;
while (-1!=(len =rdf.read(flush))){
ops.write(flush,0,(int)endpoint);
ops.flush();
}
rdf.close();
}
}
使用了面向对象的思想,将文件分割抽象化。运用了IO流相关知识。
过程中出现的问题
1.分割的起点和终点的确认
RandomAccessFile类提供的seek方法,确定了缓冲流的起点,所以在 flush 缓冲数组 的终点应该是要求的分割后文件的实际大小size,而不是在源文件中的位置。
2.Math.ceil方法的使用
ceil(double a),参数要求为double类型,如果直接传入long类型的length和size,则会返回一个错误的答案,需要将length强转为double类型,避免出错。