How should I discover test-resource files in a Maven-managed Java project?

后端 未结 4 1142
北恋
北恋 2021-02-13 21:06

I have a project that uses the normal Maven structure, e.g.

module
\\ src
  \\ main
    - java
    - resources
  \\ test
    - java
    - resources
4条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-13 21:32

    One trick would be to place a file in resources with a known name, get the URI of this file through the classloader, then construct a File from this URI, then get the parent, and list() the contents of that directory. Kind of a hack, but it should work.

    So here's what the code should look like, but place a file called MY_TEST_FILE (or whatever) in test/src/resources

    URL myTestURL = ClassLoader.getSystemResource("MY_TEST_FILE");
    File myFile = new File(myTestURL.toURI());
    File myTestDir = myFile.getParentFile();
    

    Then you have access to the directory you're looking for.

    That said, I'd be surprised if there's not a more 'maven-y' way to do it..

提交回复
热议问题