文件拆片:主要需要注意的地方是记录读取每片文件的起始位置以及最后一片文件的大小
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
public class SplitFileTest {
public static void main(String[] args) {
SplitFileTest test=new SplitFileTest();
test.slicePiecesFile(new File("E:/data/a.jpg"));
//test.slicePiecesFile(new File("E:/data/b.txt"));
List<File> fileList=new ArrayList<File>();
fileList.add(new File("E:/data/1_a.jpg"));
fileList.add(new File("E:/data/2_a.jpg"));
fileList.add(new File("E:/data/3_a.jpg"));
fileList.add(new File("E:/data/4_a.jpg"));
fileList.add(new File("E:/data/5_a.jpg"));
fileList.add(new File("E:/data/6_a.jpg"));
test.mergeFile(fileList,"E:/data/aa.jpg");
/*List<File> fileList=new ArrayList<File>();
fileList.add(new File("E:/data/1_b.txt"));
test.mergeFile(fileList,"E:/data/bb.txt");*/
}
public void slicePiecesFile(File fileName)
{
Base64 base=new Base64();
long uploadTime=System.currentTimeMillis()/1000;
int fileIndex=1; //文件分片下表
long perPiece = 1024*60;//默认每个分片文件的大小
long start=0,end = 0;
long fileSize=0;//文件大小
String fileNameTmp=null;
if (fileName.exists() && fileName.isFile()) {
fileSize=fileName.length();
fileNameTmp=fileName.getName();
System.out.println("文件"+fileName+"的大小是:"+fileName.length());
}
//计算需要拆分的次数
int num=(int) (fileSize/perPiece);
if(fileSize%perPiece != 0)
num++;
//分片上传文件信息
System.out.println("创建随机读写文件");
RandomAccessFile randomAccessFile=null;
FileOutputStream fos=null;
try {
randomAccessFile=new RandomAccessFile(fileName,"r");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
System.out.println("进入拆分文件");
byte[] buff = null;
//循环读取文件信息
for(int i=1;i<=num;i++)
{
if(i== num && fileSize%perPiece != 0)
buff = new byte[(int) (fileSize%perPiece)];
else
buff = new byte[(int)perPiece];
try
{
randomAccessFile.seek(start);//从指定位置开始读取
randomAccessFile.read(buff);
fos=new FileOutputStream("E:\\data\\"+i+"_"+fileNameTmp);
fos.write(buff);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
start+=buff.length;
System.out.println(start);
}
System.out.println("拆分文件结束");
}
public void mergeFile(List<File> fileList,String FileName)
{
FileOutputStream fos=null;
FileInputStream fis=null;
System.out.println("合并文件开始");
try
{
fos=new FileOutputStream(new File(FileName));
byte[] buff=new byte[1024];
int length=0;
for(File file:fileList)
{
fis=new FileInputStream(file);
while((length=fis.read(buff)) != -1)
{
fos.write(buff,0,length);
fos.flush();
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try {
fos.close();
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("合并文件结束");
}
}