文件切割分为两种情况。
对于像pdf这样的文件分割,需要借助第三方依赖jar包提供的api处理。以pdf切割为例:
<dependency>
<groupId>com.lowagie</groupId>
<artifactId>itext</artifactId>
<version>2.1.7</version>
</dependency>
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class PdfUtil {
public static void main(String[] args) {
partitionPdfFile("E:\\dashi\\itsm\\file\\MongoDB权威指南.pdf","MongoDB权威指南第一章.pdf", 1,24);
}
/**
* 截取pdfFile的第from页至第end页,组成一个新的文件名
* @param pdfFile 源文件
* @param newFile 切割后的文件名
* @param from 开始页
* @param end 结束页
*/
public static void partitionPdfFile(String pdfFile,
String newFile, int from, int end) {
Document document = null;
PdfCopy copy = null;
try {
PdfReader reader = new PdfReader(pdfFile);
int n = reader.getNumberOfPages();
if(end==0){
end = n;
}
ArrayList<String> savepaths = new ArrayList<String>();
String staticpath = pdfFile.substring(0, pdfFile.lastIndexOf("\\")+1);
String savepath = staticpath+ newFile;
savepaths.add(savepath);
document = new Document(reader.getPageSize(1));
copy = new PdfCopy(document, new FileOutputStream(savepaths.get(0)));
document.open();
for(int j=from; j<=end; j++) {
document.newPage();
PdfImportedPage page = copy.getImportedPage(reader, j);
copy.addPage(page);
}
document.close();
} catch (IOException e) {
e.printStackTrace();
} catch(DocumentException e) {
e.printStackTrace();
}
}