java 如何获取JAR文件中资源目录中的所有资源?

lp0sw83n  于 2023-09-29  发布在  Java
关注(0)|答案(3)|浏览(112)

我正在使用Sping Boot ,我想获取资源。
下面是我的目录结构:

├───java
│   └───...
├───resources
│   └───files
│       ├───file1.txt
│       ├───file2.txt
│       ├───file3.txt
│       └───file4.txt

我正在尝试获取files目录中的资源。以下是我访问这些文件的方法:

@Autowired
private ResourceLoader resourceLoader;

...
Stream<Path> walk = Files.walk(Paths.get(resourceLoader.getResource("classpath:files/").getURI()));

当文件位于target目录中时,它可以在本地运行,但当我从JAR文件运行它时,找不到文件。我该如何解决此问题?我已经检查了这些文件确实存在于BOOT-INF/classes/files下的jar中。
下面是maven如何构建资源并将其复制到MySQL中的(我不希望过滤.txt文件):

<resources>
  <resource>
    <directory>src/main/resources</directory>
    <filtering>true</filtering>
    <excludes>
      <exclude>**/*.txt</exclude>
    </excludes>
  </resource>
  <resource>
    <directory>src/main/resources</directory>
    <filtering>false</filtering>
    <includes>
      <include>**/*.txt</include>
    </includes>
  </resource>
</resources>
nbnkbykc

nbnkbykc1#

你可以尝试用下面的代码来读取文件吗?

ResourcePatternResolver resourcePatResolver = new PathMatchingResourcePatternResolver();
Resource[] AllResources = resourcePatResolver.getResources("classpath*:files/*.txt");
 for(Resource resource: AllResources) {
    InputStream inputStream = resource.getInputStream();
    //Process the logic
 }

这不是您所编写代码的确切解决方案,但它将给予有关要阅读的资源的大纲。

omqzjyyz

omqzjyyz2#

其他人也遇到了和你一样的问题,他们按照Sambit的建议,通过将ResourceLoader和ResourcePatternResolver结合起来找到了解决方案。在这里看到相同的问题与答案:https://stackoverflow.com/a/49826409/6777695

mgdq6dx1

mgdq6dx13#

下面的示例代码在基于Windows的本地开发环境下读取/加载了配置为rules/文件夹的一部分的Drools文件,该文件夹位于/src/main/resources项目路径下。作为IDE的一部分,而在基于Linux/Unix的生产环境中,则来自应用程序jar。
在本地Windows开发环境中使用 java.lang.ClassLoader.getResource(String name) 方法读取/加载文件的方法,而在基于Linux的生产环境中部署时,使用 org.springframework.core.io.support.ResourcePatternUtils.getResourcePatternResolver(ResourceLoader resourceLoader) returned org.springframework.core.io.support.ResourcePatternResolver.getResources(String locationPattern) 方法从应用程序jar读取/加载文件。

**注意:**如果您在Windows环境下使用命令行执行应用程序jar,则上述示例将不起作用,使用以下命令:

java -jar questionaries-rules-0.0.1-SNAPSHOT.jar

在这种情况下,您需要调用 loadResourcesOfRulesFromJar() 方法,使其在Windows或Linux/Unix环境中工作。
您可以根据自己的需求添加逻辑,以便在本地开发环境和prod环境之间进行切换,或者考虑操作系统类型沿着一些配置机制,以满足开发和部署需求。
Drools配置

/**
 * @author dinesh.lomte
 */
package com.dl.questioneries.rules.api.config;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.kie.api.KieServices;
import org.kie.api.builder.KieBuilder;
import org.kie.api.builder.KieFileSystem;
import org.kie.api.runtime.KieContainer;
import org.kie.internal.io.ResourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternUtils;

import com.dl.questioneries.rules.api.exception.SystemException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Configuration
public class DroolsConfiguration {

    private final KieServices kieServices = KieServices.Factory.get();
    private ResourceLoader resourceLoader;

    /**
     * 
     * @param resourceLoader
     */
    @Autowired
    public DroolsConfiguration(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
    
    /**
     * 
     * @return
     * @throws SystemException
     */
    @Bean
    public KieContainer kieContainer() throws SystemException {

        KieFileSystem kieFileSystem = kieServices.newKieFileSystem();

        File[] files = 
                System.getProperty("os.name").contains("Windows")
                ? loadResourcesOfRulesFromLocalSystem()
                : loadResourcesOfRulesFromJar();
        if (files == null || files.length == 0) {
            String message = "Failed to load the '.drl' files located under resources specific rules folder.";
            log.error(message);
            throw new SystemException(
                    "SYS_ERROR_00001", message, new Exception(message));
        }
        for (File file : files) {
            kieFileSystem.write(ResourceFactory.newFileResource(file));
        }
        log.info("Loaded the configured rule files successfully.");
        KieBuilder Kiebuilder = kieServices.newKieBuilder(kieFileSystem);
        Kiebuilder.buildAll();

        return kieServices.newKieContainer(
                kieServices.getRepository().getDefaultReleaseId());
    }
    
    /**
     * 
     * @return
     */
    private File[] loadResourcesOfRulesFromJar() {
        
        log.info("Loading the configured rule files from Jar.");
        Resource[] resources = null;
        List<File> files = new ArrayList<>();
        try {
            resources = ResourcePatternUtils
                    .getResourcePatternResolver(resourceLoader)
                    .getResources("classpath*:rules/*.drl");
            InputStream inputStream = null;
            File file = null;
            for (Resource resource : resources) {
                try {
                    inputStream = resource.getInputStream();
                    file = File.createTempFile(
                            resource.getFilename().substring(
                                    0, resource.getFilename().length() - 4), 
                            ".drl");
                    FileUtils.copyInputStreamToFile(inputStream, file);
                } finally {
                    inputStream.close();
                }
                log.info("'{}'", resource.getFilename());
                files.add(file);
            }
        } catch (IOException ioException) {
            String message = new StringBuilder(
                    "Failed to load the '.drl' files located under resources specific rules folder.")
                    .append(ioException.getMessage()).toString();
            log.error(message, ioException);
            throw new SystemException(
                    "SYS_ERROR_00001", message, ioException);
        }
        return (File[]) files.toArray(new File[files.size()]);
    }
    
    /**
     * 
     * @return
     */
    private File[] loadResourcesOfRulesFromLocalSystem() {
        
        log.info("Loading the configured rule files from local system.");
        try {
            File files = new File(
                    getClass().getClassLoader().getResource("rules/").getPath());
            return files.listFiles();
        } catch (Exception exception) {
            String message = new StringBuilder(
                    "Failed to load the '.drl' files located under resources specific rules folder.")
                    .append(exception.getMessage()).toString();
            log.error(message, exception);
            throw new SystemException(
                    "SYS_ERROR_00001", message, exception);
        }
    }
}

静止控制器

/**
 * @author dinesh.lomte
 */
package com.dl.questioneries.rules.api.controller;

import org.kie.api.runtime.KieContainer;
import org.kie.api.runtime.KieSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.dl.questioneries.rules.api.model.Question;

@RestController
public class QuestioneriesRulesController {

    @Autowired
    private KieContainer kieContainer;

    /**
     * 
     * @param question
     * @return
     */
    @PostMapping(path = "/getQuestion", 
            consumes = MediaType.APPLICATION_JSON_VALUE,
            produces = MediaType.APPLICATION_JSON_VALUE)
    public Question fetchQuestion(@RequestBody Question question) {
        
        KieSession kieSession = kieContainer.newKieSession();
        kieSession.insert(question);
        kieSession.fireAllRules(1);
        
        return question;
    }
}

相关问题