How to get a path to a resource in a Java JAR file

前端 未结 16 2415
时光说笑
时光说笑 2020-11-22 09:23

I am trying to get a path to a Resource but I have had no luck.

This works (both in IDE and with the JAR) but this way I can\'t get a path to a file, only the file

16条回答
  •  无人共我
    2020-11-22 09:44

    Inside your ressources folder (java/main/resources) of your jar add your file (we assume that you have added an xml file named imports.xml), after that you inject ResourceLoader if you use spring like bellow

    @Autowired
    private ResourceLoader resourceLoader;
    

    inside tour function write the bellow code in order to load file:

        Resource resource = resourceLoader.getResource("classpath:imports.xml");
        try{
            File file;
            file = resource.getFile();//will load the file
    ...
        }catch(IOException e){e.printStackTrace();}
    

提交回复
热议问题