package com.xbl.test; |
002 |
003 | import java.io.File; |
004 | import java.io.RandomAccessFile; |
005 |
006 | import org.junit.Test; |
007 | /** |
008 |
* <p>[SplitImageUtil]描述:文件分割工具类</p> |
009 |
* @作者 xbl |
010 |
* @日期 2011年2月25日 11:31:54 |
011 |
*/ |
012 | public class SplitImageUtil { |
013 |
014 |
015 | /** |
016 | * <p>拆分文件</p> |
017 | * @param file 源文件 |
018 | * @param count 拆分的文件个数 |
019 | * @throws Exception |
020 | */ |
021 | public static void split(String file , int count) throws Exception |
022 | { |
023 | |
024 | RandomAccessFile raf = new RandomAccessFile( new File(file), "r" ); |
025 | long length = raf.length(); |
026 | |
027 | long theadMaxSize = length / count; //每份的大小 1024 * 1000L; |
028 | raf.close(); |
029 |
030 | long offset = 0L; |
031 | for ( int i= 0 ;i< count- 1 ;i++) //这里不去处理最后一份 |
032 | { |
033 | long fbegin = offset; |
034 | long fend = (i+ 1 ) * theadMaxSize; |
035 | offset =write(file,i,fbegin,fend); |
036 | } |
037 |
038 | if (length- offset> 0 ) //将剩余的都写入最后一份 |
039 | write(file,count- 1 ,offset,length); |
040 | } |
041 | /** |
042 | * <p>指定每份文件的范围写入不同文件</p> |
043 | * @param file 源文件 |
044 | * @param index 文件顺序标识 |
045 | * @param begin 开始指针位置 |
046 | * @param end 结束指针位置 |
047 | * @return |
048 | * @throws Exception |
049 | */ |
050 | private static long write(String file, int index, long begin, long end) throws Exception |
051 | { |
052 | RandomAccessFile in = new RandomAccessFile( new File(file), "r" ); |
053 | RandomAccessFile out = new RandomAccessFile( new File(file+ "_" +index+ ".tmp" ), "rw" ); |
054 | byte [] b = new byte [ 1024 ]; |
055 | int n= 0 ; |
056 | in.seek(begin); //从指定位置读取 |
057 |
058 | while (in.getFilePointer() <= end && (n= in.read(b))!=- 1 ) |
059 | { |
060 | out.write(b, 0 , n); |
061 | } |
062 | long endPointer =in.getFilePointer(); |
063 | in.close(); |
064 | out.close(); |
065 | return endPointer; |
066 | } |
067 | /** |
068 | * <p>合并文件</p> |
069 | * @param file 指定合并后的文件 |
070 | * @param tempFiles 分割前的文件名 |
071 | * @param tempCount 文件个数 |
072 | * @throws Exception |
073 | */ |
074 | public static void merge(String file,String tempFiles, int tempCount) throws Exception |
075 | { |
076 | RandomAccessFile ok = new RandomAccessFile( new File(file), "rw" ); |
077 |
078 | for ( int i= 0 ;i<tempCount;i++) |
079 | { |
080 | RandomAccessFile read = new RandomAccessFile( new File(tempFiles+ "_" +i+ ".tmp" ), "r" ); |
081 | byte [] b = new byte [ 1024 ]; |
082 | int n= 0 ; |
083 | while ((n=read.read(b))!= - 1 ) |
084 | { |
085 | ok.write(b, 0 , n); |
086 | } |
087 | read.close(); |
088 | } |
089 | ok.close(); |
090 | } |
091 | @Test |
092 | public void testSplit() throws Exception |
093 | { |
094 | SplitImageUtil.split( "c:\\http_imgload.jpg" , 5 ); |
095 | } |
096 | @Test |
097 | public void testMerge() throws Exception |
098 | { |
099 | SplitImageUtil.merge( "c:\\3dd.jpg" , "c:\\http_imgload.jpg" , 5 ); |
100 | } |
101 |
102 | } |