文件的分割与合并
public class FileDivisionUniyer
{
/**
* 文件分割合并器 将大文件分割成若干个小文件,将多个小文件合并成一个大文件
*/
public static final String SUFFIX = ".pp";
public static String[] divde(String fileName, long size) throws Exception
{
File file = new File(fileName);
if (!file.exists() || !file.isFile())
throw new Exception("指定文件不存在");
File paretFile = file.getParentFile();
long fileLength = file.length();// 大文件的大小
int num = 0;// 被分割成小文件的数量
if (size <= 0)// 除数不能为0
{
size = fileLength / 2;
}
if (fileLength % size == 0)
{
num = (int) (fileLength / size);
} else
num = (int) (fileLength / size + 1);
String[] outFileName = new String[num + 5];
long endFile = 0;
int begainFile = 0;
FileInputStream in = new FileInputStream(file);
System.out.println(num);
for (int i = 0; i < num; i++)
{
File file2 = new File(paretFile, file.getName() + i + SUFFIX);
FileOutputStream out = new FileOutputStream(file2);// 如果文件不存在 在这里会新建一个文件 但是如果文件夹(目录)不存在会出错(不会新建)
endFile += size;
if (endFile > fileLength)
endFile = fileLength;
for (; begainFile < endFile; begainFile++)
out.write(in.read());
out.close();
System.out.println(begainFile);
outFileName[i] = file2.getAbsolutePath();
}
return outFileName;
}
public static void unit(String[] fileName, String newFileName) throws Exception
{
File file = new File(newFileName);
FileOutputStream out = new FileOutputStream(file);//在这里如果目录存在而文件不想在会在此目录下新建一个文件,但是 目录不存在时会出错
for (int i = 0; i < fileName.length; i++)
{
file = new File(fileName[i]);
FileInputStream in = new FileInputStream(file);
int c = 0;
while ((c = in.read()) != -1)
{
out.write(c);
}
in.close();
}
out.close();
}
public static void main(String[] args)
{
String fileNameString = "C:/temp/newTemp.pdf";
try
{
String[] strings = divde(fileNameString, 0);
unit(strings, "C:/hahaha1.pdf");
} catch (Exception e)
{
// TODO: handle exception
e.printStackTrace();
}
}
}
梦里不知身是客,一晌贪欢。