3 Answers
3

If you want to keep your code, you can try to change the working directory in the run/debug configuration (first entry in the combo box giving access to what you want to run)
Set this to your module root.
But prefer the other suggested approach:

ClassLoader.getSystemResourceAsStream(youPath)

Or my preferred:

getClass.getResource(youPath)

or

getClass.getResourceAsStream(youPath)

A leading '/' in path indicates the working dir of your project, while no '/' indicates a relative dir to current class.

I use this last solution for my tests: I put my test data resources at the same package level as the test source, or in a subdir to avoid too messy package.

This way I can do a simple call without complicated path and without having to deal with working directory:

I set the junit working directory to $MODULE_DIR$ and it works as expected. Unfortunatly it's not possible to use this variable in default junit configuration ! What a shame...
–
tbruyelleApr 12 '11 at 16:19

$MODULE_DIR$ isn't suggested in the default junit configuration, but you can force the value in the "working configuration" field avec it works!
–
tbruyelleApr 12 '11 at 16:41

Don't use the system class loader....... getClass().getResourceAsStream(youPath) would only work if the resources are in that class's JAR file (if it was packaged in a separate JAR) - you need to do use class.getClassloader() or Thread.currentThread().contextClassLoader() to reliably load from anywhere on the classpath
–
iangreenJun 23 '12 at 2:48

@iangreen: Are you really sure it's the case - would You mind quoting docs?
–
RekinMay 9 '13 at 20:29

Be aware that this alters your default JUnit launch configuration. Therefore, it won't alter any configurations that you already have created. If this solution doesn't work for you, double check which configuration you are actually using and whether it has inherited this value correctly.
–
Rupert Madden-AbbottFeb 21 '14 at 11:15

be careful if you are using groovy in your project: ClassLoader.getSystemResourceAsStream can stop working (return always null) because intellij starts to use a command line wrapper / dynamic proxy. See to disable this feature jguru.com/faq/view.jsp?EID=1533847. I've lost so many hours trying to figure what was happening...
–
GuillaumeApr 12 '11 at 15:50

Thanks I'm aware of those stuff, but I need to retrieve a File which can't be in the classpath because its path is configured in some parameters. I really need a solution with relative path.
–
tbruyelleApr 12 '11 at 15:54

I think you should to use getClass().getClassLoader().getClassLoader (or the thread context class loader) - not the system class loader. that's probably why it doesn't work sometimes.
–
iangreenJun 23 '12 at 2:50