How to deal with relative path in Junits between Maven and Intellij

前端 未结 5 1627
臣服心动
臣服心动 2021-01-30 08:37

I have a maven project with a module

/myProject
pom.xml
    /myModule
    pom.xml
       /foo
       bar.txt

Consider a Junit in myModule

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-30 09:32

    a) Don't use Files, use InputStreams. get your InputStream via

    ClassLoader.getSystemResourceAsStream("foo/bar.xml")
    

    Most APIs that deal with Files are happy with InputStreams as well.

    b) Don't use foo directories, use directories both maven and your IDE know about (i.e. put them in src/main/resources or src/test/resources, so they are on the Class Path)

    c) If you have an API that absolutely needs a File, not an InputStream, you can still do

    new File(ClassLoader.getSystemResource("foo/bar.xml").toURI())
    

提交回复
热议问题