访问包中的文件 [英] Access a file in package

查看:52
本文介绍了访问包中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JUnit在我的应用程序上执行一些自动化测试,这些测试位于JUnit类包中名为tests的文件夹中. 到目前为止,我使用以下命令访问文件:

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?

谢谢

推荐答案

如果要使用类加载器加载测试数据,则不能使用File. File实例代表文件系统中的路径.该类从文件系统,jar文件,zip文件或其他位置加载文件.因此,类加载器不允许您访问文件,但可以访问资源.

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.

使用MyClass.class.getResourceAsStream("/the/absolute/path.txt")加载path.txt文件的内容作为输入流.该文件必须在类路径中的任何位置:path.txt是在文件系统中还是在jar中,只要在类路径的包the.absolute中可以找到就无关紧要.因此,如果数据文件位于测试文件夹中,该文件夹位于测试的sources目录下,则使用的路径应为/tests/data.txt.请注意,这是可行的,因为Eclipse通过将非Java文件复制到输出目录(传统上是bin或类)来自动编译"文件,并且在运行测试时此目录位于类路径中.

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.

如果要将此数据作为文本而不是字节加载,只需用InputStreamReader包裹InputStream.

If you want to load this data as text rather than bytes, just wrap the InputStream with an InputStreamReader.

这篇关于访问包中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆