Home > Java > javaTutorial > body text

How to implement jar operation in springboot and copy resources files to the specified directory

PHPz
Release: 2023-05-12 21:34:04
forward
1613 people have browsed it

springboot implements jar operation and copies resources files to the specified directory

1. Requirements

During the project development process, all resources in the project resources/static/ directory need to be copied to the specified directory. . In the company project, video files need to be downloaded. Since the download has an html page, the corresponding static resource files are used to load the multi-channel video, such as js, css.jwplayer, jquery.js and other files

The path of the jar generated by maven is different from the path of the usually released project, so when reading the path, the path of the jar is obtained, and the file path in the jar cannot be obtained

2. Idea

Based on For my needs, the idea of ​​copying is to first obtain the file list in the resources/static/blog directory, and then copy the files to the specified location in a loop through the list (the relative paths need to be consistent)

Because the project will It is classified into a jar package, so the traditional directory file copying method cannot be used. Spring Resource is required here:

Resource interface, which is simply the abstract access interface for resources of the entire Spring framework. It inherits from the InputStreamSource interface. Subsequent articles will analyze it in detail.

Method description of Resource interface:

##exists() Determine whether the resource exists, true means it exists. isReadable()Determine whether the content of the resource is readable. It should be noted that when the result is true, its content may not really be readable, but if it returns false, its content must not be readable. isOpen() Determine whether the underlying resource represented by the current Resource has been opened. If true is returned, it can only be read once and then closed to avoid resource leakage; This method is mainly aimed at InputStreamResource. In the implementation class, only its return result is true, and the others are false. getURL()Returns the URL corresponding to the current resource. An exception will be thrown if the current resource cannot be resolved into a URL. For example, ByteArrayResource cannot be parsed into a URL. getURI()Returns the URI corresponding to the current resource. An exception will be thrown if the current resource cannot be resolved into a URI. getFile()Returns the File corresponding to the current resource. contentLength()Returns the length of the current resource contentlastModified()Returns the current The last modification time of the underlying resource represented by Resource. createRelative()Create a new resource based on the relative path of the resource. [Creating relative path resources is not supported by default]getFilename()Get the file name of the resource. getDescription()Returns the descriptor of the underlying resource of the current resource, which is usually the full path of the resource (actual file name or actual URL address). getInputStream()Get the input stream represented by the current resource. Except for the InputStreamResource implementation class, other Resource implementation classes will return a brand new InputStream every time they call the getInputStream() method.
Method Description
Get the Resource list, I need to get the resources through the ResourceLoader interface, here I chose

org.springframework.core.io.support.PathMatchingResourcePatternResolver

3. Implementation code

/**
     * 只复制下载文件中用到的js
     */
    private void copyJwplayer() {
        //判断指定目录下文件是否存在
        ApplicationHome applicationHome = new ApplicationHome(getClass());
        String rootpath = applicationHome.getSource().getParentFile().toString();
        String realpath=rootpath+"/vod/jwplayer/";   //目标文件
        String silderrealpath=rootpath+"/vod/jwplayer/silder/";   //目标文件
        String historyrealpath=rootpath+"/vod/jwplayer/history/";   //目标文件
        String jwplayerrealpath=rootpath+"/vod/jwplayer/jwplayer/";   //目标文件
        String layoutrealpath=rootpath+"/vod/jwplayer/res/layout/";   //目标文件
        /**
         * 此处只能复制目录中的文件,不能多层目录复制(目录中的目录不能复制,如果循环复制目录中的目录则会提示cannot be resolved to URL because it does not exist)
         */
        //不使用getFileFromClassPath()则报[static/jwplayerF:/workspace/VRSH265/target/classes/static/jwplayer/flvjs/] cannot be resolved to URL because it does not exist
        //jwplayer
        File fileFromClassPath = FreeMarkerUtil.getFileFromClassPath("/static/jwplayer/");  //复制目录
        FreeMarkerUtil.BatCopyFileFromJar(fileFromClassPath.toString(),realpath);
        //silder
        File flvjspath = FreeMarkerUtil.getFileFromClassPath("/static/jwplayer/silder/");  //复制目录
        FreeMarkerUtil.BatCopyFileFromJar(flvjspath.toString(),silderrealpath);
        //history
        File historypath = FreeMarkerUtil.getFileFromClassPath("/static/jwplayer/history/");  //复制目录
        FreeMarkerUtil.BatCopyFileFromJar(historypath.toString(),historyrealpath);
        //jwplayer
        File jwplayerpath = FreeMarkerUtil.getFileFromClassPath("/static/jwplayer/jwplayer/");  //复制目录
        FreeMarkerUtil.BatCopyFileFromJar(jwplayerpath.toString(),jwplayerrealpath);
        //layout
        File layoutpath = FreeMarkerUtil.getFileFromClassPath("/static/jwplayer/res/layout/");  //复制目录
        FreeMarkerUtil.BatCopyFileFromJar(layoutpath.toString(),layoutrealpath);
    }
Copy after login

4. Tool class FreeMarkerUtil

package com.aio.util;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import java.io.*;

/**
 * @author:hahaha
 * @creattime:2021-12-02 10:33
 */

public class FreeMarkerUtil {

   
    /**
     * 复制path目录下所有文件
     * @param path  文件目录 不能以/开头
     * @param newpath 新文件目录
     */
    public static void BatCopyFileFromJar(String path,String newpath) {
        if (!new File(newpath).exists()){
            new File(newpath).mkdir();
        }
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            //获取所有匹配的文件
            Resource[] resources = resolver.getResources(path+"/*");
            //打印有多少文件
            for(int i=0;i<resources.length;i++) {
                Resource resource=resources[i];
                try {
                    //以jar运行时,resource.getFile().isFile() 无法获取文件类型,会报异常,抓取异常后直接生成新的文件即可;以非jar运行时,需要判断文件类型,避免如果是目录会复制错误,将目录写成文件。
                    if(resource.getFile().isFile()) {
                        makeFile(newpath+"/"+resource.getFilename());
                        InputStream stream = resource.getInputStream();
                        write2File(stream, newpath+"/"+resource.getFilename());
                    }
                }catch (Exception e) {
                    makeFile(newpath+"/"+resource.getFilename());
                    InputStream stream = resource.getInputStream();
                    write2File(stream, newpath+"/"+resource.getFilename());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 创建文件
     * @param path  全路径 指向文件
     * @return
     */
    public static boolean makeFile(String path) {
        File file = new File(path);
        if(file.exists()) {
            return false;
        }
        if (path.endsWith(File.separator)) {
            return false;
        }
        if(!file.getParentFile().exists()) {
            if(!file.getParentFile().mkdirs()) {
                return false;
            }
        }
        try {
            if (file.createNewFile()) {
                return true;
            } else {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    /**
     * 输入流写入文件
     *
     * @param is
     *            输入流
     * @param filePath
     *            文件保存目录路径
     * @throws IOException
     */
    public static void write2File(InputStream is, String filePath) throws IOException {
        OutputStream os = new FileOutputStream(filePath);
        int len = 8192;
        byte[] buffer = new byte[len];
        while ((len = is.read(buffer, 0, len)) != -1) {
            os.write(buffer, 0, len);
        }
        os.close();
        is.close();
    }
    /**
    *处理异常报错(springboot读取classpath里的文件,解决打jar包java.io.FileNotFoundException: class path resource cannot be opened)
    **/
    public static File getFileFromClassPath(String path){
        File targetFile = new File(path);
        if(!targetFile.exists()){
            if(targetFile.getParent()!=null){
                File parent=new File(targetFile.getParent());
                if(!parent.exists()){
                    parent.mkdirs();
                }
            }
            InputStream initialStream=null;
            OutputStream outStream =null;
            try {
                Resource resource=new ClassPathResource(path);
                //注意通过getInputStream,不能用getFile
                initialStream=resource.getInputStream();
                byte[] buffer = new byte[initialStream.available()];
                initialStream.read(buffer);
                outStream = new FileOutputStream(targetFile);
                outStream.write(buffer);
            } catch (IOException e) {
            } finally {
                if (initialStream != null) {
                    try {
                        initialStream.close(); // 关闭流
                    } catch (IOException e) {
                    }
                }
                if (outStream != null) {
                    try {
                        outStream.close(); // 关闭流
                    } catch (IOException e) {
                    }
                }
            }
        }
        return targetFile;
    }
}
Copy after login

5. Effect

How to implement jar operation in springboot and copy resources files to the specified directory

The above is the detailed content of How to implement jar operation in springboot and copy resources files to the specified directory. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template