Home  >  Article  >  Java  >  How to implement jar operation in springboot and copy resources files to the specified directory

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

PHPz
PHPzforward
2023-05-12 21:34:041429browse

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);
    }

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

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete