Java实现文件操作及打包

流保存成文件
中间件:Aspose 
操作world可以,获取pdf文件流构建new Document(in)时会报异常,异常内容如下:
com.aspose.words.UnsupportedFileFormatException: Unknown file format: Unknown
从work流转pdf可以用doc.save(os, SaveFormat.PDF);

保存文件:
InputStream in = fileService.getContent(Long.parseLong(attachments[i].getCode()));
//pdf不能用aspose保存
File pdf = new File(sourcePath + File.separator + attachments[i].getName());
if (pdf.exists()) {
      pdf.delete();
  }
  pdf.createNewFile();
  FileOutputStream fos = new FileOutputStream(pdf);
  int flag = 0;
  while ((flag = in.read()) != -1) {
      fos.write(flag);
  }
  
try{
	 if(fos != null){
         fos.close();
     }
      if(in != null){
         in.close();
     }
}catch(Exception e){
	System.out.println("downloadTemplatesAtts pdf流关闭异常");
}
Aspose中间件操作word

Aspose(付费)可操作word的多种功能,改内容、加水印图片、加二维码等常用操作。

word文件另存为:
in = fileService.getContent(Long.parseLong(attachments[i].getCode()));
doc = new Document(in);
os = new FileOutputStream(sourcePath + File.separator + attachments[i].getName());
if(suffix.equals("doc")){
   doc.save(os, SaveFormat.DOC); //另存为.doc
}else if(suffix.equals("docx")){
    doc.save(os, SaveFormat.DOCX); //另存为.docx
}else if(suffix.equals("docm")){
    doc.save(os, SaveFormat.DOCM); //另存为.docm
}else if(suffix.equals("pdf")){
    doc.save(os, SaveFormat.PDF); //另存为.pdf
}else {
	continue;
}

try{
	if(os != null){
           os.flush();
           os.close();
       }
       if(in != null){
           in.close();
       }
}catch(Exception e){
	System.out.println("downloadTemplatesAtts word流关闭异常");
}
java实现Zip打包
**中文名称及内容不乱码**
需要的包:
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.charset.Charset;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
  * 文件压缩
  * @param zipPath ZIP文件路径 xx/xx/x/x.zip
  * @param SourcePath	需要压缩的目录
  */
public void doZip(String zipPath,String SourcePath){
		System.out.println("开始压缩,源文件夹路径:" + zipPath + "/ZIP文件路径:" + zipPath);
		File sourceDir = new File(SourcePath);
		// 生成压缩包名称 位置
		File zipFile = new File(zipPath);
		// 创建ZipOutputStream 流 jdk7 自动关闭 FileOutputStream
		try (ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile))){
		    WritableByteChannel writableByteChannel = Channels.newChannel(zipOut);
		    // 开始时间
		    long start = System.currentTimeMillis();
		    // 循环压缩文件
		    File files[] = sourceDir.listFiles();
		    for (File file:files) {
		        try(FileChannel in = new FileInputStream(file).getChannel()){
		            // 向压缩文件目录 中 添加文件压缩后名称
		            zipOut.putNextEntry(new ZipEntry(file.getName()));
		            in.transferTo(0,file.length(),writableByteChannel);
		        }
		    }
		    // 结束时间
		    long end = System.currentTimeMillis();
		    // 总用时间 
		    System.out.println("压缩完成,耗时:" + (end - start) + "ms");
		} catch (FileNotFoundException e) {
			 System.out.println("压缩异常,文件不存在:" + e.getLocalizedMessage());
		} catch (IOException e) {
			System.out.println("压缩异常:" + e.getLocalizedMessage());
		}
	}

调用
String zipPath = "D:\\ZipTest\\test.zip";
String sourcePath = "D:\\ZipTest\\AAa";
doZip(zipPath,sourcePath);
response.setContentType("application/x-download"); //告知浏览器下载
response.setHeader("Content-Disposition", "attachment;filename=" + zipName);//下载名称
ServletOutputStream out = response.getOutputStream();
FileInputStream zipIn = new FileInputStream(zipPath);
byte[] buffer = new byte[1024];
int len = 0;
while((len=zipIn.read(buffer)) != -1){
	out.write(buffer,0,len);
}
try{
	if(zipIn != null){
		zipIn.close();
	}
	
	if(dirZipSource.exists() && dirZipSource.isDirectory()){
		dirZipSource.delete();
       }
	if(zip.exists()){
		zip.delete();
       }
}catch(Exception e){
	System.out.println("关闭异常:" + e.getLocalizedMessage());
}
递归删除文件或文件夹
/**
 * 先根遍历序递归删除文件夹
 *
 * @param dirFile 要被删除的文件或者目录
 * @return 删除成功返回true, 否则返回false
 */
protected boolean deleteFile(File dirFile) {
    // 如果dir对应的文件不存在,则退出
    if (!dirFile.exists()) {
        return false;
    }
    if (dirFile.isFile()) {
        return dirFile.delete();
    } else {
        for (File file : dirFile.listFiles()) {
            deleteFile(file);
        }
    }
    // 目录此时为空,可以删除
    return dirFile.delete();
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值