天天看點

java檔案分割合并_檔案分割合并類(java)

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

import java.io.RandomAccessFile;

// 檔案分割類

public class FILECut {

private OutputStream ou;

private File file;

private long fileLength;

private byte[] buf;

private RandomAccessFile saveFile;

public FILECut(String f)

{

file = new File(f);

if (file.exists())

{

fileLength = file.length();

}

else

{

fileLength = 0;

}

}

public void Cut(int n, String fn, String tgt) throws IOException

{

File fe;

int seeklen = 0;

int tpLen = 0;

int tpDe = 0;

if (fileLength%n==0)

{

tpLen = (int)(fileLength/n);

}

else

{

tpLen = (int)(fileLength/n);

tpDe = (int)(fileLength%n);

}

saveFile = new RandomAccessFile(file, "r");

saveFile.seek(0);

for (int i=1; i<=n; i++)

{

fe = new File(file.getParent()+"\\"+fn+"_"+i+"."+tgt);

if (i

{

if (tpLen!=0)

{

buf = new byte[tpLen];

saveFile.read(buf);

ou = new FileOutputStream(fe);

ou.write(buf);

seeklen+=tpLen;

saveFile.seek(seeklen);

buf = null;

}

}

else if(i==n)

{

if (tpDe!=0)

{

buf = new byte[tpLen+tpDe];

saveFile.read(buf);

ou = new FileOutputStream(fe);

ou.write(buf);

buf = null;

}

}

}

saveFile.close();

}

}

import java.io.File;

import java.io.FileInputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.RandomAccessFile;

//檔案合并類

public class FILEHut {

private static File[] fileList;

private static RandomAccessFile saveFile;

private static InputStream in;

private static byte[] buf;

private static Boolean isCutFile(File f, String tg)

{

String file = f.getName();

String hz = file.substring(file.lastIndexOf(".")+1).toLowerCase();

if (hz.compareTo(tg)==0)

{

return true;

}

return false;

}

public static void Hut(String fname, String tgt) throws IOException

{

File f = new File(new File(fname).getParent());

fileList = f.listFiles();

int seeklen = 0;

saveFile = new RandomAccessFile(fname, "rw");

saveFile.seek(0);

for (int i=0; i

{

if (isCutFile(fileList[i], tgt)==true)

{

in = new FileInputStream(fileList[i]);

buf = new byte[(int) fileList[i].length()];

in.read(buf);

saveFile.write(buf);

seeklen+=(int) fileList[i].length();

saveFile.seek(seeklen);

}

}

saveFile.close();

}

}

使用詳解:

FILECut file = new FILECut("D:\\cut\\cut.txt"); //分割檔案路徑

file.Cut(3, "btt","tt"); //分割份數 字首檔案名 字尾檔案名(格式.tt)

FILEHut.Hut("D:\\cut\\cd.exe", "tt"); //将制定目錄下得所有格式為tt的檔案合成cd.exe