项目知识盲区五

x33g5p2x  于2021-12-30 转载在 其他  
字(7.6k)|赞(0)|评价(0)|浏览(137)

java压缩文件

package dhy.com.utils;

import dhy.com.exception.CustomException;
import dhy.com.exception.CustomExceptionType;

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;
   //默认的生成的压缩包名字
    private static final String DEFAULT_ZIP_NAME="dhy.zip";
   //默认是否保留原来的目录结构
    private static final Boolean SAVE_ORIGINAL_STRUCTURE=true;
    /** * 压缩成ZIP * @param srcDir 要压缩的文件夹的路径 */
    public static void toZip(String srcDir) throws FileNotFoundException
    {
        File file = new File(srcDir);
        if(!file.exists())
        {
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR,"下载的资源不存在");
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file.getParent()+File.separator+DEFAULT_ZIP_NAME);
        toZip(srcDir,fileOutputStream,SAVE_ORIGINAL_STRUCTURE);
    }

    /** * 压缩成ZIP * @param srcDir 要压缩的文件夹的路径 * @param zipFileName 生成的压缩文件的名字 */
    public static void toZip(String srcDir,String zipFileName) throws FileNotFoundException
    {
        File file = new File(srcDir);
        if(!file.exists())
        {
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR,"下载的资源不存在");
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file.getParent()+File.separator+DEFAULT_ZIP_NAME);
        toZip(srcDir,fileOutputStream,SAVE_ORIGINAL_STRUCTURE);
    }

    /** * 压缩成ZIP * @param srcDir 压缩文件夹路径 * @param KeepDirStructure 是否保留原来的目录结构 */
    public static void toZip(String srcDir, boolean KeepDirStructure) throws FileNotFoundException {
        File file = new File(srcDir);
        if(!file.exists())
        {
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR,"下载的资源不存在");
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file.getParent()+File.separator+DEFAULT_ZIP_NAME);
        toZip(srcDir,fileOutputStream,KeepDirStructure);
    }

    /** * 压缩成ZIP * @param srcDir 压缩文件夹路径 * @param KeepDirStructure 是否保留原来的目录结构 * @param zipFileName 生成的压缩文件的名字 */
    public static void toZip(String srcDir,String zipFileName ,boolean KeepDirStructure) throws FileNotFoundException {
        File file = new File(srcDir);
        if(!file.exists())
        {
            throw new CustomException(CustomExceptionType.USER_INPUT_ERROR,"下载的资源不存在");
        }
        FileOutputStream fileOutputStream = new FileOutputStream(file.getParent()+File.separator+DEFAULT_ZIP_NAME);
        toZip(srcDir,fileOutputStream,KeepDirStructure);
    }

    /** * 压缩成ZIP 方法1 * @param srcDir 压缩文件夹路径 * @param out 压缩文件输出流 * @param KeepDirStructure 是否保留原来的目录结构,true:保留目录结构; * false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败) * @throws RuntimeException 压缩失败会抛出运行时异常 */
    private 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实现文件上传与下载

//下载爬取到的图片
    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指定

<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>

相关文章