java文件分割合并_java 实现文件分割与合并的代码(转)

package com.neusoft.common.file;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

/**

* 文件工具类

*/

public class FileUtils {

public static void main(String[] args) {

File file = new File("E:/360Downloads/test.pdf");

try {

String[] names = divideFile(file.getAbsolutePath(),1000,".pdf");

for(int i = 0;i < names.length;i++) {

System.out.println(names[i]);

}

uniteFile(names,"E:/test.pdf");

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

/**

* 分割文件

* @param fileName 待分割的文件名

* @param size 小文件的大小,以字节为单位

* @param suffix 生成的文件名后缀

* @return 分割后的小文件的文件名

* @throws Exception 分割过程中可能抛出的异常

*/

public static String[] divideFile(String fileName, long size, String suffix) throws Exception {

File inFile = new File(fileName);

if (!inFile.exists() || inFile.isDirectory()) {

throw new Exception("not found file.");

}

File parentFile = inFile.getParentFile();

long fileLength = inFile.length();

if (size <= 0) {

size = fileLength / 2;

}

int num = (int) ((fileLength + size - 1) / size);

String[] outFileNames = new String[num];

FileInputStream in = new FileInputStream(inFile);

long inEndIndex = 0;

int inBeginIndex = 0;

for (int outFileIndex = 0; outFileIndex < num; outFileIndex++) {

File outFile = new File(parentFile, inFile.getName() + outFileIndex + suffix);

FileOutputStream out = new FileOutputStream(outFile);

inEndIndex += size;

inEndIndex = (inEndIndex > fileLength) ? fileLength : inEndIndex;

for (; inBeginIndex < inEndIndex; inBeginIndex++) {

out.write(in.read());

}

out.close();

outFileNames[outFileIndex] = outFile.getAbsolutePath();

}

in.close();

return outFileNames;

}

/**

* 合并文件

* @param fileNames 待合并的文件名,是一个数组

* @param targetFileName 目标文件名

* @return 目标文件的全路径

* @throws Exception 合并过程中可能抛出的异常

*/

public static String uniteFile(String[] fileNames, String targetFileName) throws Exception {

File inFile = null;

File outFile = new File(targetFileName);

FileOutputStream out = new FileOutputStream(outFile);

for (int i = 0; i < fileNames.length; i++) {

inFile = new File(fileNames[i]);

FileInputStream in = new FileInputStream(inFile);

int c;

while ((c = in.read()) != -1) {

out.write(c);

}

in.close();

}

out.close();

return outFile.getAbsolutePath();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值