I am using JUnit to do some automated tests on my application, the tests are in a folder called tests in my JUnit classes package.
As of now, I access the files using the following:
File file = new File(MyClass.class.getResource("../path/to/tests/" + name).toURI());
Is there a cleaner (and nicer) way to do it?
Thanks
If you want to use the classloader to load your test data, then you can’t use
File. AFileinstance represents a path in the file system. The class loads files from the file system, or from jar files, or from zip files, or from somewhere else. The class loader thus doesn’t let you access files, but resources.Use
MyClass.class.getResourceAsStream("/the/absolute/path.txt")to load the contents, as an input stream, of the path.txt file. This file must be anywhere in the classpath: whether path.txt is in the file system or in a jar doesn’t matter as soon as it can be found in the classpath, in the packagethe.absolute. So if your data files are in a tests folder, which is just under the sources directory of your tests, the path to use should be/tests/data.txt. Note that this works because Eclipse automatically “compiles” files which are not Java files by just copying them to the output directory (bin or classes, traditionally), and that this directory is in the classpath when you run your tests.If you want to load this data as text rather than bytes, just wrap the
InputStreamwith anInputStreamReader.