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<n)
{
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<fileList.length; 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