简体   繁体   English

如何从外部项目目录读取资源文件?

[英]How can I read resources file from outside project directory?

Below code works fine if file location is resources folder but when file location is outside the project directory like(c:\file.json) it fails.如果文件位置是资源文件夹,下面的代码可以正常工作,但是当文件位置在项目目录之外时,如 (c:\file.json),它会失败。 How can we load file from outside project directory.我们如何从外部项目目录加载文件。

    @Bean
    public UserInfo readFile() {
        String fileName="prop.json";
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
        File file = new File(classLoader.getResource(fileName).getFile());
        try {
             UserInfo info= new ObjectMapper(new JsonFactory()).readValue(file, UserInfo.class);
        } catch (Exception e) {
            
        }
        return info;
    }

You should create a Configuration class that implements WebMvcConfigurer and override the addResourceHadndler Method to add new resource to spring context.您应该创建一个实现WebMvcConfigurer的配置 class 并覆盖addResourceHadndler方法以将新资源添加到 spring 上下文。

@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer{

    @Override
    public  void addResourceHandlers(ResourceHandlerRegistry registry) {
        
        // register you resource here
    }
    
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从jar中的资源中获取文件或目录列表? - How can I get file or directory list from the resources in the jar? Jetty 7.4.2 + Quercus 4.0.18:如何从 webapp 目录之外读取 PHP 文件 - Jetty 7.4.2 + Quercus 4.0.18: How can I read PHP files from outside the webapp directory 如何从WAR中的classes目录中读取文件? - How can I read file from classes directory in my WAR? 如何从外部Web内容目录中读取文件 - How to read file from outside web content directory 如何在“ war”文件之外建立目录:(在项目目录之外) - How do I make a directory outside the 'war' file : (Outside the project directory) 如何从活动外部访问我的资源? - How can I access my resources from outside of an Activity? Maven项目-从资源文件夹(项目根目录)外部加载文件 - Maven project - load file from outside of resources folder (project root) 如何使该Huffman项目从文件中读取? - How can I make this Huffman project read from file? 如何读取Java资源文件夹中的文件? - How can I read my file which is in a resources folder in Java? 如何访问位于项目文件夹外部和项目类路径外部的.properties文件? - How can I access to a .properties file situated outside the project folder and outside the project classpath?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM