前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >项目知识盲区五

项目知识盲区五

作者头像
大忽悠爱学习
发布2021-12-27 08:32:52
4120
发布2021-12-27 08:32:52
举报
文章被收录于专栏:c++与qt学习

项目知识盲区五

java压缩文件

代码语言:javascript
复制
package dhy.com.utils;


import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUtils
{
    //默认的缓冲区大小
    private static final int  BUFFER_SIZE = 2 * 1024;


    /**
     * 压缩成ZIP
     * @param srcDir 压缩文件夹路径
     */
    public static void toZip(String srcDir) throws FileNotFoundException {
        BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(new File(srcDir)));
        toZip(srcDir,out,true);
    }
    
    /**
     * 压缩成ZIP
     * @param srcDir 压缩文件夹路径
     */
    public static void toZip(String srcDir, boolean KeepDirStructure) throws FileNotFoundException {
        BufferedOutputStream out=new BufferedOutputStream(new FileOutputStream(new File(srcDir)));
        toZip(srcDir,out,KeepDirStructure);
    }

    /**
     * 压缩成ZIP 方法1
     * @param srcDir 压缩文件夹路径
     * @param out    压缩文件输出流
     * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
     * 							false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(String srcDir, OutputStream out, boolean KeepDirStructure)
            throws RuntimeException{
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            File sourceFile = new File(srcDir);
            //源文件,输出流,压缩文件的路径,是否保持目录结构
            compress(sourceFile,zos,sourceFile.getName(),KeepDirStructure);
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 压缩成ZIP 方法2
     * @param srcFiles 需要压缩的文件列表
     * @param out 	        压缩文件输出流
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(List<File> srcFiles , OutputStream out)throws RuntimeException {
        long start = System.currentTimeMillis();
        ZipOutputStream zos = null ;
        try {
            zos = new ZipOutputStream(out);
            for (File srcFile : srcFiles) {
                byte[] buf = new byte[BUFFER_SIZE];
                zos.putNextEntry(new ZipEntry(srcFile.getName()));
                int len;
                FileInputStream in = new FileInputStream(srcFile);
                while ((len = in.read(buf)) != -1){
                    zos.write(buf, 0, len);
                }
                zos.closeEntry();
                in.close();
            }
            long end = System.currentTimeMillis();
            System.out.println("压缩完成,耗时:" + (end - start) +" ms");
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils",e);
        }finally{
            if(zos != null){
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 递归压缩方法
     * @param sourceFile 源文件
     * @param zos		 zip输出流
     * @param name		 压缩后的名称
     * @param KeepDirStructure  是否保留原来的目录结构,true:保留目录结构;
     * 							false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception
     */
    private static void compress(File sourceFile, ZipOutputStream zos, String name,
                                 boolean KeepDirStructure) throws Exception{
        byte[] buf = new byte[BUFFER_SIZE];
        if(sourceFile.isFile()){
            // 向zip输出流中添加一个zip实体,构造器中name为zip实体的文件的名字
            zos.putNextEntry(new ZipEntry(name));
            // copy文件到zip输出流中
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1){
                zos.write(buf, 0, len);
            }
            // Complete the entry
            zos.closeEntry();
            in.close();
        } else {
            File[] listFiles = sourceFile.listFiles();
            if(listFiles == null || listFiles.length == 0){
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                if(KeepDirStructure){
                    // 空文件夹的处理
                    zos.putNextEntry(new ZipEntry(name + "/"));
                    // 没有文件,不需要文件的copy
                    zos.closeEntry();
                }

            }else {
                for (File file : listFiles) {
                    // 判断是否需要保留原来的文件结构
                    if (KeepDirStructure) {
                        // 注意:file.getName()前面需要带上父文件夹的名字加一斜杠,
                        // 不然最后压缩包中就不能保留原来的文件结构,即:所有文件都跑到压缩包根目录下了
                        compress(file, zos, name + "/" + file.getName(),KeepDirStructure);
                    } else {
                        compress(file, zos, file.getName(),KeepDirStructure);
                    }

                }
            }
        }
    }
}

使用ZipEntry压缩与解压缩

java实现文件打包压缩处理

java文件压缩工具类,打包zip

工具类2:用java进行多文件压缩为一个ZIP包

Java实现将文件或者文件夹压缩成zip

ZipOutputStream、ZipFile、ZipInputStream

Java IO操作——掌握压缩流的使用(ZipOutputStream、ZipFile、ZipInputStream)[java.util包中]

ZipOutputStream使用

CRC32 算法

在远距离数据通信中,为确保高效而无差错地传送数据,必须对数据进行校验即差错控制。循环冗余校验CRC(Cyclic Redundancy Check/Code)是对一个传送数据块进行校验,是一种高效的差错控制方法。

CRC32 算法

Java安全管理器SecurityManager

Java安全管理器SecurityManager

文件下载

SpringBoot实现文件下载

Spring Boot实现文件上传与下载

代码语言:javascript
复制
//下载爬取到的图片
    public void downLoad()  {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        HttpSession session = requestAttributes.getRequest().getSession();
        //用户是否开启了爬虫线程----主要判断session,如果为空,抛出异常
         if(session==null)
             throw new CustomException(CustomExceptionType.USER_INPUT_ERROR,"请先爬取再下载资源");
        String sessionID =session.getId();
        //判断当前用户的爬虫线程是否关闭
        List<JobDetail> userClawerList = getUserClawerList();
        //当前用户开启了一个爬虫线程,还未关闭,不能继续开启爬虫线程
        if (userClawerList != null && userClawerList.size() == 1) {
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR, "请先关闭已经开启的爬虫线程");
        }

        //TODO:将下载的图片,的文件夹进行打包
        String zipPath="";
        try {
            zipPath = FileUtils.toZip(clawerProperties.getFilePathPrefix() + sessionID + "/");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }


        HttpServletResponse response = requestAttributes.getResponse();
        File file = new File(zipPath);
        if (file == null||!file.exists())
            throw new CustomException(CustomExceptionType.SYSTEM_ERROR, "下载的文件不存在");
        response.setContentType("application/octet-stream");
        response.setHeader("content-type", "application/octet-stream");
        try {
            response.addHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(file.getName(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] buffer = new byte[1024];
        OutputStream os=null;
        try (FileInputStream fis = new FileInputStream(file);
             BufferedInputStream bis = new BufferedInputStream(fis))
        {
             os = response.getOutputStream();
            int i = -1;
            while ((i = bis.read(buffer)) != -1) {
                os.write(buffer, 0, i);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            //删除文件压缩包
            FileUtils.delFile(zipPath);
        }
    }

no main manifest attribute, in xxxx.jar 项目部署报错

no main manifest attribute, in xxxx.jar 项目部署报错

找不到main方法,需要我们在pom.xml指定

代码语言:javascript
复制
  <build>
         <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <includeSystemScope>true</includeSystemScope>
                    <mainClass>com.qiruipeng.eureka.EurekaApplication</mainClass>
                </configuration>
            </plugin>
        </plugins>
    </build>
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/12/23 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 项目知识盲区五
  • java压缩文件
  • ZipOutputStream、ZipFile、ZipInputStream
  • CRC32 算法
  • Java安全管理器SecurityManager
  • 文件下载
  • no main manifest attribute, in xxxx.jar 项目部署报错
相关产品与服务
文件存储
文件存储(Cloud File Storage,CFS)为您提供安全可靠、可扩展的共享文件存储服务。文件存储可与腾讯云服务器、容器服务、批量计算等服务搭配使用,为多个计算节点提供容量和性能可弹性扩展的高性能共享存储。腾讯云文件存储的管理界面简单、易使用,可实现对现有应用的无缝集成;按实际用量付费,为您节约成本,简化 IT 运维工作。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档