How to read a file created at runtime?

Using Java 8.

Basically, in unit test (junit), I have this code:

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

In callSomeCode()I have this:

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

When you first start the test , it this.getClass().getResource("/img/dest/someImage.gif")returns null, although the file is well created.

The second time (when the file was already created during the first test run, and then simply overwritten), it is not equal to zero and the test passes.

How to make it work for the first time?
Do I have to configure a special setting in IntelliJ to automatically update the folder in which the file was created?

Note that I have this basic maven structure:

--src
----test
------resources   
+4
source share
2 answers

nakano531 - , classpath. , getClass().getResource(...), , , .

, :

callSomeCode();
File file = new File("src/test/resources/img/dest/someImage.gif");
assertTrue(file.exists());

, .

- , nakano531: fooobar.com/questions/95055/...

+2

, - , , . :

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

Source: https://habr.com/ru/post/1660608/


All Articles