How to access file in the static resources(WEB-INF) folder from the referencing java project?

后端 未结 4 717
感情败类
感情败类 2021-01-15 02:00

I have a web application, that contains a configuration xml file for one of my application services that is exposed as spring bean. Also I have a standalone java application

4条回答
  •  无人及你
    2021-01-15 02:24

    Definitely keep the file under WEB-INF/ folder if that's where it is supposed to live.

    For your test classes that are being executed from the command line. Your can use getClassLoader().getResource() on a file that you know is in the root of your classpath (e.g. application.properties file). From there you know the structure of your project and where to find WEB-INF/ relative to the properties file. Since it returns a URL you can use it to figure out a path to the XML files you're looking for.

    URL url = this.getClass().getClassLoader().getResource("application.properties");
    System.out.println(url.getPath());
    
    File file = new File(url.getFile());
    System.out.println(file);
    
    // now use the Files' path to obtain references to your WEB-INF folder
    

    Hopefully you find this useful. I have had to make assumptions about how your test classes are runing etc.

    Take a look at the File Class and it's getPath(), getAbsolutePath(), and getParent() methods that could be of use to you.

提交回复
热议问题