springboot运行jar包,实现复制jar包resources下文件夹(可支持包含子文件夹)到指定的目录

FreeMarkerUtil工具类

package org.jawa.common.utils;

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.*;
import java.util.ArrayList;

/**
 * 复制resource文件夹
 *
 * @Author zheng
 * @Date 2023/09/03 19:58:41
 * @Version 1.0
 */
public class FreeMarkerUtil {

    private static ArrayList paths=new ArrayList();
    private static ArrayList noCoberpaths=new ArrayList();

    /**
     * 复制path目录下所有文件,覆盖
     * @param path  文件目录 不能以/开头
     * @param newpath 新文件目录
     */
    public static void BatCopyFileFromJarCover(String path,String newpath) {
        if (!new File(newpath).exists()){
            new File(newpath).mkdir();
        }
        if(path.contains("\\")){
            path=path.replace("\\","/");
        }
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            //获取所有匹配的文件
            Resource[] resources = resolver.getResources("classpath:"+path+"/**/");
            //打印有多少文件
            for(int i=0;i<resources.length;i++) {
                Resource resource=resources[i];
                String[] descriptions = resource.getDescription().substring(0,resource.getDescription().length()-1).split(path.substring(1,path.length())+"/");
                if(descriptions.length>1){
                    if(descriptions[1].contains("/")){

                        if(descriptions[1].substring(descriptions[1].length()-1).equals("/")){
                            String[] afterDescriptions = descriptions[1].split("/");
                            String childPath=path;
                            for (int j=0;j<afterDescriptions.length;j++){
                                childPath=childPath+"/"+afterDescriptions[j];
                                if(!paths.contains(childPath)){
                                    paths.add(childPath);
                                    if (!new File(newpath+"/"+afterDescriptions[j]).exists()){
                                        new File(newpath+"/"+afterDescriptions[j]).mkdir();
                                    }
                                    File fileFromClassPath01 = FreeMarkerUtil.getFileFromClassPath(path+"/"+afterDescriptions[j]);  //复制目录
                                    FreeMarkerUtil.BatCopyFileFromJarCover(fileFromClassPath01.toString(),newpath+"/"+afterDescriptions[j]);
                                }
                            }
                        }
                    }else {
                        makeFile(newpath+"/"+descriptions[1]);
                        InputStream stream = resource.getInputStream();
                        write2File(stream, newpath+"/"+descriptions[1]);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 复制path目录下所有文件,不覆盖
     * @param path  文件目录 不能以/开头
     * @param newpath 新文件目录
     */
    public static void BatCopyFileFromJar(String path,String newpath) {
        if (!new File(newpath).exists()){
            new File(newpath).mkdir();
        }
        if(path.contains("\\")){
            path=path.replace("\\","/");
        }
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            //获取所有匹配的文件
            Resource[] resources = resolver.getResources("classpath:"+path+"/**/");
            //打印有多少文件
            for(int i=0;i<resources.length;i++) {
                Resource resource=resources[i];

                String[] descriptions = resource.getDescription().substring(0,resource.getDescription().length()-1).split(path.substring(1,path.length())+"/");
                if(descriptions.length>1){
                    if(descriptions[1].contains("/")){

                        if(descriptions[1].substring(descriptions[1].length()-1).equals("/")){
                            String[] afterDescriptions = descriptions[1].split("/");
                            String childPath=path;
                            for (int j=0;j<afterDescriptions.length;j++){

                                childPath=childPath+"/"+afterDescriptions[j];
                                if(!noCoberpaths.contains(childPath)){
                                    noCoberpaths.add(childPath);
                                    if (!new File(newpath+"/"+afterDescriptions[j]).exists()){
                                        new File(newpath+"/"+afterDescriptions[j]).mkdir();
                                    }
                                    File fileFromClassPath01 = FreeMarkerUtil.getFileFromClassPath(path+"/"+afterDescriptions[j]);  //复制目录
                                    FreeMarkerUtil.BatCopyFileFromJar(fileFromClassPath01.toString(),newpath+"/"+afterDescriptions[j]);
                                }
                            }
                        }
                    }else {
                        File f = new File(newpath+"/"+descriptions[1]);
                        if(!f.exists()) {
                            makeFile(newpath+"/"+descriptions[1]);
                            InputStream stream = resource.getInputStream();
                            write2File(stream, newpath+"/"+descriptions[1]);
                        }
                    }
                }
            }
        } 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;
    }
}


子文件夹的名字试了很多种方法,只能通过getDescription()获取,然后对其进行处理!!

测试接口

    /**
     * 测试
     */
    @GetMapping(value = "/test")
    public AjaxResult taskList() {
        File fileFromClassPath01 = FreeMarkerUtil.getFileFromClassPath("/software/htem/static_hcp/Volume_1/Dst_01");  //复制目录
        FreeMarkerUtil.BatCopyFileFromJar(fileFromClassPath01.toString(),"F:\\htem_task\\test");
        return AjaxResult.success();
    }

该方法是在下面的博客基础上进行完善的,增加了支持包含子文件夹的功能!!
https://blog.csdn.net/weixin_44975322/article/details/121677386

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot可以通过MultipartFile类来处理上传的文件,然后将文件保存到数据库中。具体步骤如下: 1. 在Controller中定义一个处理上传文件的方法,使用@RequestParam注解来获取上传的文件。 2. 在方法中使用MultipartFile类的getInputStream()方法获取文件的输入流,然后将输入流转换为byte数组。 3. 将byte数组保存到数据库中,可以使用JPA或者MyBatis等框架来实现。 4. 在前端页面中使用form表单来上传文件,设置enctype为multipart/form-data。 5. 在后端配置文件中设置上传文件的最大大小和临时文件存储路径等参数。 示例代码如下: @Controller public class FileUploadController { @Autowired private FileService fileService; @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) throws IOException { byte[] bytes = file.getBytes(); fileService.saveFile(bytes); return "redirect:/success"; } } @Service public class FileService { @Autowired private FileRepository fileRepository; public void saveFile(byte[] bytes) { FileEntity fileEntity = new FileEntity(); fileEntity.setFileContent(bytes); fileRepository.save(fileEntity); } } @Entity public class FileEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Lob private byte[] fileContent; // getter and setter } 参考链接:https://www.baeldung.com/spring-file-upload ### 回答2: SpringBoot是目前非常流行的Java Web开发框架,它极大地简化了Java Web开发的复杂性。而在实际开发中,图片上传和保存是非常常见的需求。本文将介绍在SpringBoot中如何实现图片上传并保存到数据库。 一、前端页面设计 在前端页面中,通常会有一个“上传文件”的按钮,用户可以通过点击该按钮,选择需要上传的图片。这个过程我们不需要过多介绍,网上的UI组件已经非常多了,大家可以根据自己的项目需求来选择。这里我们只介绍如何在SpringBoot中接收上传的图片。 二、后端代码实现 接下来,我们需要编写服务器端代码,以完成图片的接收和保存。首先需要编写一个Controller类,这个类需要使用SpringBoot提供的MultipartFile对象来接收客户端上传的图片。代码如下: ``` @RestController public class FileUploadController { @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { //将图片保存到数据库中的代码 } } ``` 在这段代码中,@PostMapping("/upload")表示这个方法只会接收POST请求,并且请求的URL为/upload。@RequestParam("file")表示这个方法要求客户端上传的图片必须命名为“file”。 接下来,我们需要将接收到的图片保存到数据库中。这里介绍两种方法: 1. 将图片保存到数据库的BLOB字段中。 ```java @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { try { byte[] bytes = file.getBytes(); String name = file.getOriginalFilename(); String type = file.getContentType(); ImageEntity imageEntity = new ImageEntity(); imageEntity.setName(name); imageEntity.setData(bytes); imageEntity.setType(type); imageRepository.save(imageEntity); // imageRepository是SpringBoot集成JPA后的仓库对象 return "上传成功!"; } catch (IOException e) { e.printStackTrace(); return "上传失败!"; } } ``` 在这个方法中,首先使用MultipartFile对象的getBytes()方法将图片内容读取到一个字节数组中,然后获取图片的文件名和类型。接着,创建一个<ImageEntity>对象,将图片内容、文件名和类型分别设置到该对象中,最后使用SpringBoot集成的JPA将该对象保存到数据库中。 2. 将图片保存到文件系统中,并将文件路径保存到数据库字段中。 ```java @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { try { String fileName = StringUtils.cleanPath(file.getOriginalFilename()); String fileBaseName = FilenameUtils.getBaseName(fileName); String fileExtension = FilenameUtils.getExtension(fileName); String absoluteFileName = System.currentTimeMillis() + "." + fileExtension; String storageDirectory = "/images/"; Path fileStorageLocation = Paths.get(storageDirectory).toAbsolutePath().normalize(); Files.createDirectories(fileStorageLocation); Path targetLocation = fileStorageLocation.resolve(absoluteFileName); Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING); ImageEntity entity = new ImageEntity(); entity.setName(fileBaseName); entity.setUrl(targetLocation.toString()); imageRepository.save(entity); return "上传成功!"; } catch (IOException ex) { ex.printStackTrace(); return "上传失败!"; } } ``` 在这段代码中,使用SpringBoot提供的文件操作类来将文件保存到指定的文件系统目录下,然后将文件的路径保存到数据库字段中。 三、总结 在实际开发过程中,图片上传和保存到数据库是非常常见的需求。在SpringBoot中,我们可以通过使用MultipartFile对象接收图片,并将图片内容存储到数据库的BLOB字段中,也可以将图片保存到文件系统中,并将文件路径存储到数据库字段中。本文简单介绍了如何使用这两种方法,希望对大家有所帮助。 ### 回答3: Spring Boot 是一款非常流行的 Java 开发框架,它可以帮助我们快速创建可靠的、高效的应用程序。本文将介绍如何使用 Spring Boot 实现上传图片保存到数据库的功能。 1. 实现文件上传。 在 Spring Boot 中,我们可以使用标准的 HTML 表单来上传文件。我们可以使用 Spring Boot 提供的 MultipartFile 类实现文件上传,这个类可以帮助我们处理上传文件的各种操作,例如获取上传文件的名称和大小等信息。 在 Spring Boot 中,文件上传的处理可以使用 @PostMapping 注解实现,代码如下所示: @PostMapping("/upload") public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) { if (file.isEmpty()) { return new ResponseEntity("请选择需要上传的文件!", HttpStatus.OK); } try { byte[] bytes = file.getBytes(); // 保存文件到本地 Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename()); Files.write(path, bytes); return new ResponseEntity("文件上传成功!", new HttpHeaders(), HttpStatus.OK); } catch (IOException e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } } 2. 实现保存图片到数据库。 在上传文件成功后,我们需要将文件的内容保存到数据库中。我们可以使用 Hibernate 框架来实现将文件内容保存到数据库的功能。 首先,我们需要在实体中定义一个属性来存储文件的二进制数据。代码如下: @Lob private byte[] data; 然后,我们需要在控制器中编写代码来将文件的内容保存到数据库中。代码如下: @PostMapping("/upload") public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file) { // ... try { byte[] bytes = file.getBytes(); Image image = new Image(); image.setFileName(file.getOriginalFilename()); image.setData(bytes); imageRepository.save(image); return new ResponseEntity("文件上传成功!", new HttpHeaders(), HttpStatus.OK); } catch (IOException e) { // ... } } 最后,我们可以编写一个简单的查询方法来从数据库中读取图片。代码如下: @GetMapping("/image/{id}") public ResponseEntity<byte[]> getImage(@PathVariable Long id) { Image image = imageRepository.findById(id).orElse(null); if (image == null) { return ResponseEntity.notFound().build(); } byte[] data = image.getData(); HttpHeaders headers = new HttpHeaders(); headers.setCacheControl(CacheControl.noCache().getHeaderValue()); return new ResponseEntity<>(data, headers, HttpStatus.OK); } 总结 以上就是使用 Spring Boot 实现上传图片保存到数据库的方法。实现这个功能并不难,只需要遵循上述步骤,即可成功上传和保存图片。值得提醒的是,如果正在处理大文件,可能需要在上传后进行异步处理,以便不影响应用程序的性能。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值