批量导出导入数据及附件文件ZIP包_导出压缩包 ,压缩包里面要包含查询的数据生成的excel 还有服务器上存储的资料文

            }
            List<ZsglFileEntity> entityList = new ArrayList<>();
            String[] fileArray = data.get("FILES").toString().split(",");
            List idList = Arrays.asList(fileArray);
            entityList.addAll(fileMapper.selectByIds(idList));
            if (CollectionUtils.isNotEmpty(entityList)){
                for (ZsglFileEntity file : entityList){
                    if ( file.getFssFileId() == null){
                        continue;
                    }
                    String fileUrl = urlPrefix + "/fss/download/" + file.getFssFileId();
                    // 构造URL
                    URL url = new URL(fileUrl);
                    // 打开连接
                    URLConnection con = url.openConnection();
                    //设置请求超时为5s
                    con.setConnectTimeout(5 \* 1000);
                    // 输入流
                    is = con.getInputStream();
                    File tempFile = new File(savePath + "/"+file.getFileName());
                    // 校验文件夹目录是否存在,不存在就创建一个目录
                    if (!tempFile.getParentFile().exists()) {
                        tempFile.getParentFile().mkdirs();
                    }
                    os = new FileOutputStream(tempFile);
                    is = con.getInputStream();
                    con.getHeaderFields();
                    IOUtils.copy(is, os);
                    System.out.println("下载完成");
                }
                entityList.clear();
            }
        }
    }catch (IOException e){
        System.err.println(e);
    }finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(os);
    }
}

### 3. 生成压缩文件(浏览器下载)



    response.setCharacterEncoding("UTF-8");
    response.setContentType("multipart/form-data");
    response.setHeader("content-disposition", "attachment;filename=" + "XX数据导出.zip");
    ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
    try {
        File[] sourceFiles = file.listFiles();
        if (null == sourceFiles || sourceFiles.length < 1) {
            System.out.println("待压缩的文件目录:" + "里面不存在文件,无需压缩.");
        } else {
            for (int i = 0; i < sourceFiles.length;i++){
                File srcFile = sourceFiles[i];
                if (srcFile.isDirectory()){
                    File[] imageSourceFiles = srcFile.listFiles();
                    if (null == imageSourceFiles || imageSourceFiles.length < 1){
                        continue;
                    }
                    for (File imageFile : imageSourceFiles){
                        compress(zos,imageFile,srcFile.getName()+"/");
                    }
                } else {
                    compress(zos,srcFile,"");
                }
            }
        }
    }catch (Exception e){
        e.printStackTrace();
    } finally {
        //关闭流
        try {
            if(null != zos) {
                zos.close();
            }
        } catch (IOException e){
            e.printStackTrace();
        }
    }

其中的压缩方法如下:



public void compress(ZipOutputStream out,File sourceFile,String base) throws Exception
{
out.putNextEntry( new ZipEntry(base+sourceFile.getName()) );
FileInputStream fos = new FileInputStream(sourceFile);
BufferedInputStream bis = new BufferedInputStream(fos);
int tag;
System.out.println(base);
//将源文件写入到zip文件中
while((tag=bis.read())!=-1) {
out.write(tag);
out.flush();
}
out.closeEntry();
bis.close();
fos.close();
}


### 4. 删除临时目录



public void deleteDirectory(File file) {
File[] list = file.listFiles(); //无法做到list多层文件夹数据
if (list != null) {
for (File temp : list) { //先去递归删除子文件夹及子文件
deleteDirectory(temp); //注意这里是递归调用
}
}
if (!file.delete()) { //再删除自己本身的文件夹
logger.error(“文件删除失败 : %s%n”, file);
}
}


## 二、导入ZIP包


### 1. 上传zip包,解压到临时目录


`这里开始想着在不解压的情况下读取里面的文件,结果没有走通。因为zip里面包含了子文件夹里面的附件信息需要解析。不解压直接解析文件适用于只需要解析zip包中第一层文件的场景,如果子文件夹下的文件也需要处理的话,最好解压后再处理。`



public void unzip(ZipInputStream zipIn, String destDirectory) throws IOException {
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdirs();
}
ZipEntry entry = zipIn.getNextEntry();
// 遍历Zip文件中的条目
while (entry != null) {
String filePath = destDirectory + File.separator + entry.getName();
if (!entry.isDirectory()) {
int index = entry.getName().indexOf(“/”);
if (index > -1 && entry.getName().length() > index){
File tempFile = new File(destDirectory + File.separator +entry.getName().substring(0,index));
if (!tempFile.exists()){
tempFile.mkdir();
}
}
File checkFile = new File(filePath);
if (!checkFile.exists()) {
checkFile.createNewFile();// 创建目标文件
}
// 如果条目是文件直接解压
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[1024];
int read = 0;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
} else {
File dir = new File(filePath);
if (!dir.exists()){
dir.mkdirs();
}
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
}


这里解压遇到了一个问题,之前导出生成的zip包直接导入没问题,但是我把导出的包手动解压后修改了部分数据重新压缩后再导入报错:`ZipInputStream解压远程文件报错,java.lang.IllegalArgumentException: MALFORMED`  
 原因:文件名含有中文,zip解析出错  
 解决方案,如下行代码,在生成ZipInputStream的时候指定编码格式。



> 
> ZipInputStream zis = new ZipInputStream(new BufferedInputStream(inputStream), Charset.forName(“GBK”));
> 
> 
> 


### 2. 读取附件信息上传到文件服务器



public List readLocalFile() throws Exception {
File file= new File(destDirectory+“/files”);
List fssList = new ArrayList<>();
if (file.exists()) {
File[] sourceFiles = file.listFiles();
if (null == sourceFiles || sourceFiles.length < 1) {
System.out.println(file.getName()+“目录里面不存在文件,无需处理.”);
return fssList;
} else {
for (int i = 0; i < sourceFiles.length;i++){
File srcFile = sourceFiles[i];
FileItemFactory factory = new DiskFileItemFactory(16, null);
FileItem item = factory.createItem(srcFile.getName(), “text/plain”, true, srcFile.getName());
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(srcFile);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {

img
img

网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。

需要这份系统化资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。**

需要这份系统化资料的朋友,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!

  • 13
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要实现导出多个Excel文件并打压缩包,可以使用Java中的ZipOutputStream类来实现。以下是一个简单的示例代码: ```java try { // 创建ZipOutputStream对象 ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream("result.zip")); // 定义要导出Excel文件列表 List<File> excelFiles = new ArrayList<>(); excelFiles.add(new File("data1.xlsx")); excelFiles.add(new File("data2.xlsx")); // 遍历Excel文件列表,逐个写入到压缩包中 for (File excelFile : excelFiles) { // 创建ZipEntry对象,指定压缩包中的文件ZipEntry entry = new ZipEntry(excelFile.getName()); zipOut.putNextEntry(entry); // 读取Excel文件内容,并将其写入到ZipOutputStream中 FileInputStream in = new FileInputStream(excelFile); byte[] buffer = new byte[1024]; int len; while ((len = in.read(buffer)) > 0) { zipOut.write(buffer, 0, len); } // 关闭ZipEntry和输入流 in.close(); zipOut.closeEntry(); } // 关闭ZipOutputStream对象 zipOut.close(); } catch (IOException e) { e.printStackTrace(); } ``` 以上示例代码创建了一个ZipOutputStream对象,然后遍历要导出Excel文件列表,逐个将其写入到压缩包中。最后关闭ZipOutputStream对象即可。需要注意的是,在写入每个Excel文件时,都需要先创建一个ZipEntry对象来指定压缩包中的文件名,并调用ZipOutputStream的putNextEntry方法来开始写入该文件;写入完成后需要调用ZipOutputStream的closeEntry方法来结束该文件的写入。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值