Access a file in package

感情迁移 提交于 2019-12-23 22:24:32

问题


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


回答1:


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.




回答2:


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());



回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/7152749/access-a-file-in-package

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!