java实现⽂件切⽚和合并的代码⽰例
最近在学习⼤数据相关的知识点,其中需要实现⽂件的切⽚和合并,完整的java实现代码,以下贴出个⼈代码,仅供参考⾸先建⼀个SplitUtil⼯具类,在⼯具类中有三个⽅法getSplitFile,getWrite,merge
1,⽂件拆分代码
public static void getSplitFile(String file,int count){
//预分配⽂件所占⽤的磁盘空间,在磁盘创建⼀个指定⼤⼩的⽂件,“r”表⽰只读,“rw”⽀持随机读写
try {
RandomAccessFile raf = new RandomAccessFile(new File(file), "r");
//计算⽂件⼤⼩
long length = raf.length();
System.out.println(length);
//计算⽂件切⽚后每⼀份⽂件的⼤⼩
long maxSize = length / count;
System.out.println(maxSize);
long offset = 0L;//定义初始⽂件的偏移量(读取进度)
//开始切割⽂件
for(int i = 0; i < count - 1; i++){ //count-1最后⼀份⽂件不处理
//标记初始化
long fbegin = offset;
//分割第⼏份⽂件
long fend = (i+1) * maxSize;
//写⼊⽂件
offset = getWrite(file, i, fbegin, fend);
}
//剩余部分⽂件写⼊到最后⼀份(如果不能平平均分配的时候)
if (length - offset > 0) {
//写⼊⽂件
getWrite(file, count-1, offset, length);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
2,getWrite⽂件写⼊代码
/**
* 指定⽂件每⼀份的边界,写⼊不同⽂件中
* @param file 源⽂件
* @param index 源⽂件的顺序标识
* @param begin开始指针的位置
* @param end 结束指针的位置
* @return long
*/
public static long getWrite(String file,int index,long begin,long end){
long endPointer = 0L;
try {
//申明⽂件切割后的⽂件磁盘
RandomAccessFile in = new RandomAccessFile(new File(file), "r");
//定义⼀个可读,可写的⽂件并且后缀名为.tmp的⼆进制⽂件
RandomAccessFile out = new RandomAccessFile(new File(file + "_" + index + ".tmp"), "rw");
//申明具体每⼀⽂件的字节数组
byte[] b = new byte[1024];
int n = 0;
//从指定位置读取⽂件字节流
in.seek(begin);
//判断⽂件流读取的边界
FilePointer() <= end && (n = in.read(b)) != -1){
//从指定每⼀份⽂件的范围,写⼊不同的⽂件
out.write(b, 0, n);
}
//定义当前读取⽂件的指针一份完整的网页代码和效果图
endPointer = in.getFilePointer();
//关闭输⼊流
in.close();
//关闭输出流
out.close();
} catch (Exception e) {
e.printStackTrace();
}
return endPointer;
}
3.⽂件合并代码
/**
* ⽂件合并
* @param file 指定合并⽂件
* @param tempFile 分割前的⽂件名
* @param tempCount ⽂件个数
*/
public static void merge(String file,String tempFile,int tempCount){
RandomAccessFile raf = null;
try {
//申明随机读取⽂件RandomAccessFile
raf = new RandomAccessFile(new File(file), "rw");
//开始合并⽂件,对应切⽚的⼆进制⽂件
for (int i = 0; i < tempCount; i++) {
//读取切⽚⽂件
RandomAccessFile reader = new RandomAccessFile(new File(tempFile + "_" + i + ".tmp"), "r");
byte[] b = new byte[1024];
int n = 0;
while((n = ad(b)) != -1){
raf.write(b, 0, n);//⼀边读,⼀边写
}
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
最后在主程序⾥⾯调⽤就可以了
public static void main(String[] args) {
String file = "F:\\java-study\\img\\mv.jpg";
int count = 5;
//1.根据现有的⽂件编写⽂件编写⽂件切⽚⼯具类
//2.写⼊到⼆进制临时⽂件
//  getSplitFile(file, count);
//3.根据实际的需求合并指定数量的⽂件
String tempFile = "F:\\java-study\\img\\img.jpg";
merge(file, tempFile, 5);
}
以上代码可实现图⽚,⽂档,mp3,mp4等⽂件的拆分与合并,下⾯是图⽚切⽚和拆分的效果图以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。