


How to implement jar operation in springboot and copy resources files to the specified directory
May 12, 2023 pm 09:34 PMspringboot 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:
Method | Description |
---|---|
Determine whether the resource exists, true means it exists. | |
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. | |
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. | |
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. | |
Returns the URI corresponding to the current resource. An exception will be thrown if the current resource cannot be resolved into a URI. | |
Returns the File corresponding to the current resource. | |
Returns the length of the current resource content | |
Returns the current The last modification time of the underlying resource represented by Resource. | |
Create a new resource based on the relative path of the resource. [Creating relative path resources is not supported by default] | |
Get the file name of the resource. | |
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). | |
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. |
/**
* 只復(fù)制下載文件中用到的js
*/
private void copyJwplayer() {
//判斷指定目錄下文件是否存在
ApplicationHome applicationHome = new ApplicationHome(getClass());
String rootpath = applicationHome.getSource().getParentFile().toString();
String realpath=rootpath+"/vod/jwplayer/"; //目標(biāo)文件
String silderrealpath=rootpath+"/vod/jwplayer/silder/"; //目標(biāo)文件
String historyrealpath=rootpath+"/vod/jwplayer/history/"; //目標(biāo)文件
String jwplayerrealpath=rootpath+"/vod/jwplayer/jwplayer/"; //目標(biāo)文件
String layoutrealpath=rootpath+"/vod/jwplayer/res/layout/"; //目標(biāo)文件
/**
* 此處只能復(fù)制目錄中的文件,不能多層目錄復(fù)制(目錄中的目錄不能復(fù)制,如果循環(huán)復(fù)制目錄中的目錄則會提示cannot be resolved to URL because it does not exist)
*/
//不使用getFileFromClassPath()則報(bào)[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/"); //復(fù)制目錄
FreeMarkerUtil.BatCopyFileFromJar(fileFromClassPath.toString(),realpath);
//silder
File flvjspath = FreeMarkerUtil.getFileFromClassPath("/static/jwplayer/silder/"); //復(fù)制目錄
FreeMarkerUtil.BatCopyFileFromJar(flvjspath.toString(),silderrealpath);
//history
File historypath = FreeMarkerUtil.getFileFromClassPath("/static/jwplayer/history/"); //復(fù)制目錄
FreeMarkerUtil.BatCopyFileFromJar(historypath.toString(),historyrealpath);
//jwplayer
File jwplayerpath = FreeMarkerUtil.getFileFromClassPath("/static/jwplayer/jwplayer/"); //復(fù)制目錄
FreeMarkerUtil.BatCopyFileFromJar(jwplayerpath.toString(),jwplayerrealpath);
//layout
File layoutpath = FreeMarkerUtil.getFileFromClassPath("/static/jwplayer/res/layout/"); //復(fù)制目錄
FreeMarkerUtil.BatCopyFileFromJar(layoutpath.toString(),layoutrealpath);
}
4. Tool class FreeMarkerUtilpackage 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 {
/**
* 復(fù)制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運(yùn)行時,resource.getFile().isFile() 無法獲取文件類型,會報(bào)異常,抓取異常后直接生成新的文件即可;以非jar運(yùn)行時,需要判斷文件類型,避免如果是目錄會復(fù)制錯誤,將目錄寫成文件。
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();
}
}
/**
* 創(chuàng)建文件
* @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();
}
/**
*處理異常報(bào)錯(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(); // 關(guān)閉流
} catch (IOException e) {
}
}
if (outStream != null) {
try {
outStream.close(); // 關(guān)閉流
} catch (IOException e) {
}
}
}
}
return targetFile;
}
}
5. Effect
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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

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.

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

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

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

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

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

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
