
Dolaameng.jpg
簡述
為什么要從jar中提取資源到本地磁盤? 如何將資源保存到本地磁盤?導出這個文件干什么?
首先上來的靈魂三問。簡單來說就是當你在服務器上測試或者support時,由于一般是沒有合適的權限去在服務器上“寫文件”,但是你運行的程序時是有這些權限的,所以你可以在程序中開一個窗口,比如定義一個API,當調用這個API的時候就可以把jar包里的資源文件導出并保存在服務器本地。
開干!
首先讓我們定義一個class類來表示從資源文件夾中提取的文件
import lombok.Builder;
import lombok.Data;
import java.util.Date;
@Data
@Builder
class FileInfo {
String fileInfo;
String fileSize;
Date lastModified;
}
然后創(chuàng)建一個幫助類來從資源文件夾中提取文件并保存到本地磁盤。
ResourceLoader 是 Springframwork 里的“臨時工”,主要用來干臟活累活的,其實就是的一個開箱即用的幫助類
import ch.qos.logback.core.util.FileUtil;
import lombok.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Date;
@Component
@RequiredArgsConstructor
@Slf4j
public class KeyTabFilesHelper {
/**
* This final ResourceLoader + @RequiredArgsConstructor will make this loader automatically wired from Spring
*/
private final ResourceLoader resourceLoader;
/**
* Extract file content from jar file's Resource folder, then save it to local disk
* @param resourceFolder relative folder under project "resource" folder
* @param resourceName resource name
* @param destPath path of local disk the resource to be saved
* @return A data class provide a summary of the file saved
*/
@SneakyThrows
public FileInfo saveAsFile(String resourceFolder, String resourceName, String destPath) {
final val resource = resourceLoader.getResource("classpath:" + resourceFolder + File.separator + resourceName);
final val path = Paths.get(destPath, resourceName);
if (!Files.exists(path)) {
log.info("File NOT exist, create it and it's missing parent folder :{}", path);
File file = new File(path.toString());
FileUtil.createMissingParentDirectories(file);
}
FileCopyUtils.copy(resource.getInputStream(), new FileOutputStream(path.toFile()));
final val fileInfo = FileInfo.builder()
.fileInfo(path.toFile().toString())
.fileSize(FileUtils.byteCountToDisplaySize(Files.size(path)))
.lastModified(new Date(path.toFile().lastModified()))
.build();
log.info("saved file to {}, file is:{}", path, fileInfo);
return fileInfo;
}
}
最后你就可以在你的Controller里定義一個新的GetMapping接口。
調用上面創(chuàng)建的方法就可以魔術般的把文件搬到服務器上了。
如果有什么總是可以給我留言或者到我的網站上聯系我
歡迎大家瀏覽關注我的公眾號 “竹書紀年的IT男”