1

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. 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;
    }
1
  • 1
    You probably shouldn't use getResource() then. This is used for resources that are embedded into the jar – ask yourself if this file will be contained in the jar. For file outside the jar (in the file system), just pass the string path to the File Commented Mar 22, 2022 at 15:20

1 Answer 1

1

You should create a Configuration class that implements WebMvcConfigurer and override the addResourceHadndler Method to add new resource to spring context.

@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer{

    @Override
    public  void addResourceHandlers(ResourceHandlerRegistry registry) {
        
        // register you resource here
    }
    
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.