JAVA 文件分割工具类

来源:互联网 发布:php表单验证代码 编辑:程序博客网 时间:2024/05/17 03:21
package com.zf.target;import java.io.File;import java.io.FileOutputStream;import java.io.RandomAccessFile;/** * 分割文件工具类   * @author zhoufeng * */public class RandomAccessFileTest {public static int splitCount = 3;//默认分割成三份/** * 分割文件   * @param filePath文件路径 * @param dirPath分割后的文件 保存目录 * @param count分割成多少份文件 * @throws Exception * 默认分割后文件名 为 "数字_文件名"   */public void splitFile(String filePath , String dirPath , int count) throws Exception{File targetFile = new File(filePath);String targetFileName = targetFile.getName();long fileLen = targetFile.length();//文件大小long everyLen = fileLen / count ;//分割后每个文件的大小splitCount = fileLen % count == 0 ? count : count + 1 ;//分割数量File dir = new File(dirPath);if(!dir.isDirectory())dir.mkdirs();//目录不存在 ,就创建目录for (int i = 0; i < splitCount ; i++) {long start = i * everyLen ;RandomAccessFile raf = new RandomAccessFile(targetFile, "rw");File childFile = new File(dir , (i + 1) +"_" + targetFileName);new Thread(new SplitFile(raf , start , childFile , everyLen)).start();}}/** * 分割文件的线程类 , 为每个子文件创建一个该线程来进行分割 ,提高效率 * @author zhoufeng * */class SplitFile implements Runnable{RandomAccessFile raf = null;long start = 0;File childFile = null ;long everyLen = 0 ;public SplitFile(){}public SplitFile(RandomAccessFile raf, long start, File childFile,long everyLen) {this.raf = raf;this.start = start;this.childFile = childFile;this.everyLen = everyLen;}public void run() {try{FileOutputStream fos = new FileOutputStream(childFile);byte[] temp = new byte[1024];int len = -1;long totalLen = 0;//读到的总长度raf.seek(start);//设置开始位置if(everyLen < 1024){//如果分割后文件大小  没有比1024都小   ,就直接读取文件大小的内容  避免多读 temp = new byte[(int) everyLen];}while(totalLen < everyLen && ((len = raf.read(temp)) != -1)){fos.write(temp, 0, len);totalLen += len;if(everyLen - totalLen < 1024)//判断剩余内容还有没有1024大  ,如果没有 ,就直接读取剩下的长度避免多读temp = new byte[(int) (everyLen - totalLen)];}}catch(Exception e){e.printStackTrace();}System.out.println("线程 " + Thread.currentThread().getName() + " 分割完成");}}public static void main(String[] args) throws Exception {new RandomAccessFileTest().splitFile("C:/Documents and Settings/zhoufeng/My Documents/Downloads/HotelInfo.xml.CS/ProductionApplications/Distribution/ContentStaticInfoGenerator/output/1.HotelInfo.xml", "d:/lllllll",5 );}}