/**
* 解压缩
* @throws IOException
*/
public String compressAndUn() throws IOException{
File file=new File(sourceWordAddress);//取得word文件
String dir=ServletActionContext.getRequest().getRealPath("")+"\\zipFile\\"; //取得要解压缩文件到的目录
FileInputStream inputStream=new FileInputStream(file);
ZipInputStream zipInputStream=new ZipInputStream(inputStream);
ZipEntry entry=null;
byte ch[]=new byte[256];
while((entry=zipInputStream.getNextEntry())!=null){
File zFile=new File(dir+entry.getName());
if(entry.isDirectory()){
if(!zFile.exists()){
zFile.mkdirs();
}
zipInputStream.closeEntry();
}else{
File fpath=new File(zFile.getParent());
if(!fpath.exists()){
fpath.mkdirs();
}
FileOutputStream outputStream=new FileOutputStream(zFile);
int i;
while((i=zipInputStream.read(ch))!=-1){
outputStream.write(ch, 0, i);
}
zipInputStream.closeEntry();
outputStream.close();
}
}
inputStream.close();
此时解压缩word文件后,会产生很多xml文件,位于word文件夹中的document.xml文件包含了word的内容及样式,对此xml利用dom4j进行修改或替换即可
ZipOutputStream zipOutputStream=new ZipOutputStream(new FileOutputStream(new File(ServletActionContext.getRequest().getRealPath("")
+"\\targetFile\\test"+UUID.randomUUID().toString()+".docx"))); //要压缩文件的路径及名称
String root=ServletActionContext.getRequest().getRealPath("")+"\\zipFile\\";
String current=ServletActionContext.getRequest().getRealPath("")+"\\zipFile\\";
File rootFile=new File(root);
File currentFile=new File(current);
addAllFiles(zipOutputStream,rootFile,currentFile);
zipOutputStream.close();
return SUCCESS;
}
//压缩word解压缩产生的文件
private void addAllFiles(ZipOutputStream zipOutputStream, File current,File root) throws IOException {
byte buffer[]=new byte[4096];
int bytesIndex;
String entries[]=current.list();
for(int i=0;i<entries.length;i++){
File f=new File(current,entries[i]);
if(f.isDirectory()){
addAllFiles(zipOutputStream, f, root);
continue;
}
String relativePath=getRelativePath(current,root);
FileInputStream fileInputStream=new FileInputStream(f);
if(!relativePath.equals("")){
relativePath=relativePath+"/";
}
ZipEntry entry=new ZipEntry(relativePath+f.getName());
zipOutputStream.putNextEntry(entry);
while((bytesIndex=fileInputStream.read(buffer))!=-1){
zipOutputStream.write(buffer, 0, bytesIndex);
}
fileInputStream.close();
}
}
private static String getRelativePath(File currentFile,File rootFile){
int len=rootFile.getPath().length();
String rePath=currentFile.getPath().substring(len);
if(rePath.length()>0){
rePath = rePath.substring(1);
}
return rePath;
}
欢迎加入我的QQ交流群425783133