Table of Contents
springboot implements jar operation and copies resources files to the specified directory
1. Requirements
2. Idea
Home Java javaTutorial 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

May 12, 2023 pm 09:34 PM
jar springboot resources

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to run jar files in Linux How to run jar files in Linux Feb 20, 2024 am 10:40 AM

Prerequisites for running JAR files Running JAR files on a Linux system requires the installation of the Java Runtime Environment (JRE), which is the basic component required to execute Java applications, including the Java Virtual Machine (JVM), core class libraries, etc. Many mainstream Linux distributions, such as Ubuntu, Debian, Fedora, openSUSE, etc., provide software libraries of JRE packages to facilitate user installation. The following article will detail the steps to install JRE on popular distributions. After setting up the JRE, you can choose to use the command line terminal or the graphical user interface to start the JAR file according to your personal preference. Your choice may depend on familiarity with Linux shells and personal preference

How Springboot integrates Jasypt to implement configuration file encryption How Springboot integrates Jasypt to implement configuration file encryption Jun 01, 2023 am 08:55 AM

Introduction to Jasypt Jasypt is a java library that allows a developer to add basic encryption functionality to his/her project with minimal effort and does not require a deep understanding of how encryption works. High security for one-way and two-way encryption. , standards-based encryption technology. Encrypt passwords, text, numbers, binaries... Suitable for integration into Spring-based applications, open API, for use with any JCE provider... Add the following dependency: com.github.ulisesbocchiojasypt-spring-boot-starter2. 1.1Jasypt benefits protect our system security. Even if the code is leaked, the data source can be guaranteed.

How SpringBoot integrates Redisson to implement delay queue How SpringBoot integrates Redisson to implement delay queue May 30, 2023 pm 02:40 PM

Usage scenario 1. The order was placed successfully but the payment was not made within 30 minutes. The payment timed out and the order was automatically canceled. 2. The order was signed and no evaluation was conducted for 7 days after signing. If the order times out and is not evaluated, the system defaults to a positive rating. 3. The order is placed successfully. If the merchant does not receive the order for 5 minutes, the order is cancelled. 4. The delivery times out, and push SMS reminder... For scenarios with long delays and low real-time performance, we can Use task scheduling to perform regular polling processing. For example: xxl-job Today we will pick

How to use Redis to implement distributed locks in SpringBoot How to use Redis to implement distributed locks in SpringBoot Jun 03, 2023 am 08:16 AM

1. Redis implements distributed lock principle and why distributed locks are needed. Before talking about distributed locks, it is necessary to explain why distributed locks are needed. The opposite of distributed locks is stand-alone locks. When we write multi-threaded programs, we avoid data problems caused by operating a shared variable at the same time. We usually use a lock to mutually exclude the shared variables to ensure the correctness of the shared variables. Its scope of use is in the same process. If there are multiple processes that need to operate a shared resource at the same time, how can they be mutually exclusive? Today's business applications are usually microservice architecture, which also means that one application will deploy multiple processes. If multiple processes need to modify the same row of records in MySQL, in order to avoid dirty data caused by out-of-order operations, distribution needs to be introduced at this time. The style is locked. Want to achieve points

How to solve the problem that springboot cannot access the file after reading it into a jar package How to solve the problem that springboot cannot access the file after reading it into a jar package Jun 03, 2023 pm 04:38 PM

Springboot reads the file, but cannot access the latest development after packaging it into a jar package. There is a situation where springboot cannot read the file after packaging it into a jar package. The reason is that after packaging, the virtual path of the file is invalid and can only be accessed through the stream. Read. The file is under resources publicvoidtest(){Listnames=newArrayList();InputStreamReaderread=null;try{ClassPathResourceresource=newClassPathResource("name.txt");Input

Comparison and difference analysis between SpringBoot and SpringMVC Comparison and difference analysis between SpringBoot and SpringMVC Dec 29, 2023 am 11:02 AM

SpringBoot and SpringMVC are both commonly used frameworks in Java development, but there are some obvious differences between them. This article will explore the features and uses of these two frameworks and compare their differences. First, let's learn about SpringBoot. SpringBoot was developed by the Pivotal team to simplify the creation and deployment of applications based on the Spring framework. It provides a fast, lightweight way to build stand-alone, executable

How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables How to implement Springboot+Mybatis-plus without using SQL statements to add multiple tables Jun 02, 2023 am 11:07 AM

When Springboot+Mybatis-plus does not use SQL statements to perform multi-table adding operations, the problems I encountered are decomposed by simulating thinking in the test environment: Create a BrandDTO object with parameters to simulate passing parameters to the background. We all know that it is extremely difficult to perform multi-table operations in Mybatis-plus. If you do not use tools such as Mybatis-plus-join, you can only configure the corresponding Mapper.xml file and configure The smelly and long ResultMap, and then write the corresponding sql statement. Although this method seems cumbersome, it is highly flexible and allows us to

How SpringBoot customizes Redis to implement cache serialization How SpringBoot customizes Redis to implement cache serialization Jun 03, 2023 am 11:32 AM

1. Customize RedisTemplate1.1, RedisAPI default serialization mechanism. The API-based Redis cache implementation uses the RedisTemplate template for data caching operations. Here, open the RedisTemplate class and view the source code information of the class. publicclassRedisTemplateextendsRedisAccessorimplementsRedisOperations, BeanClassLoaderAware{//Declare key, Various serialization methods of value, the initial value is empty @NullableprivateRedisSe

See all articles