Access a file in package
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?
开发者_如何学JAVAThanks
If you want to use the classloader to load your test data, then you can't use File
. A File
instance 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 package the.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 InputStream
with an InputStreamReader
.
A better way is using of the method getFile() from URL, like so:
File file = new File(MyClass.class.getResource("../path/to/tests/" + name).getFile());
Your data would fit more inside your /tests/ folder. It would avoid you to use a relative path starting from MyClass and would be more logical. Also, you could give my class a file paramater to load the data file. It would then be called both with production data and with tests data.
Regards, Stéphane
I make sure they're in the classpath, and then use
MyClass.class.getResourceAsStream("../path/to/tests/" + name);
I'm not sure it's much better, though. What don't you like about what you use now?
This works because/when the resource file is in the classpath. This is done for you for free when it's in the source path in Eclipse or Intellij. If you're doing automated testing using Hudson or something like that, you'll need to make sure that your build process (Ant, Maven, shell script, whatever) puts them in the classpath as well.
精彩评论