有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何读取运行时创建的文件?

使用Java8

基本上,在单元测试(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   

共 (1) 个答案

  1. # 1 楼答案

    我也遇到了同样的情况,一个解决办法是延迟执行从运行时创建的文件中读取的行。使用这个:

    callSomeCode();
    Thread.sleep(6000);
    assertTrue(new File(this.getClass().getResource("/img/dest/someImage.gif").getFile()).exists());