使用 Java 8。
基本上,在单元测试 (junit) 中我有这段代码:
callSomeCode();
assertTrue(new File(this.getClass().getResource("/img/dest/someImage.gif").getFile()).exists());
在 callSomeCode()
中,我有这个:
InputStream is = bodyPart.getInputStream();
File f = new File("src/test/resources/img/dest/" + bodyPart.getFileName()); //filename being someImage.gif
FileOutputStream fos = new FileOutputStream(f);
byte[] buf = new byte[40096];
int bytesRead;
while ((bytesRead = is.read(buf)) != -1)
fos.write(buf, 0, bytesRead);
fos.close();
第一次测试运行时,this.getClass().getResource("/img/dest/someImage.gif")
返回null
虽然文件很好已创建。
第二次(当文件在第一次测试运行时已经创建然后被覆盖),它是非空的并且测试通过。
如何让它第一次工作?
我应该在 IntelliJ 中配置一个特殊设置来自动刷新创建文件的文件夹吗?
请注意,我有这个基本的 Maven 结构:
--src
----test
------resources
最佳答案
正如 nakano531 的评论所指出的那样 - 您的问题不在于文件系统,而在于类路径。您正在尝试通过调用 getClass().getResource(...)
方法使用类加载器读取文件,而不是使用直接访问文件系统的类读取文件。
例如,如果您是这样编写测试的:
callSomeCode();
File file = new File("src/test/resources/img/dest/someImage.gif");
assertTrue(file.exists());
您不会遇到现在遇到的问题。
您的另一个选择是通过 nakano531 提供的链接实现解决方案:https://stackoverflow.com/a/1011126/1587791
关于java - 如何读取运行时创建的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40569991/