简体   繁体   English

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

[英]How to read a file created at runtime?

Using Java 8. 使用Java 8。

Basically, in a unit test (junit) I have this code: 基本上,在单元测试(junit)中我有这样的代码:

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

In callSomeCode() , I have this: 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(); 

The first time the test runs, this.getClass().getResource("/img/dest/someImage.gif") returns null although the file is well created. 第一次运行测试时, this.getClass().getResource("/img/dest/someImage.gif")返回null尽管文件创建良好。

The second time (when the file was already created during the first test run then just overwritten), it is non-null and the test passes. 第二次(当文件在第一次测试运行期间已经创建然后被覆盖时),它是非空的并且测试通过。

How to make it work the first time? 如何让它第一次工作?
Should I configure a special setup in IntelliJ to automatically refresh the folder where the file is created? 我应该在IntelliJ中配置一个特殊设置来自动刷新创建文件的文件夹吗?

Note that I have this basic maven structure: 请注意,我有这个基本的maven结构:

--src
----test
------resources   

As the comment by nakano531 points out - your problem is not with the file system, but with the classpath. 正如nakano531的评论所指出的那样 - 你的问题不是文件系统,而是类路径。 You're trying to read your file using a classloader by invoking the getClass().getResource(...) methods rather than reading the file using classes that access the file system directly. 您正在尝试使用类加载器通过调用getClass().getResource(...)方法来读取文件,而不是使用直接访问文件系统的类来读取文件。

For example, if you had written your test like this: 例如,如果您已经编写了这样的测试:

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

You wouldn't have had the issue you're having now. 你不会遇到你现在遇到的问题。

Your other option is to implement the solution from the link that nakano531 provided: https://stackoverflow.com/a/1011126/1587791 您的另一个选择是从nakano531提供的链接实施解决方案: https ://stackoverflow.com/a/1011126/1587791

i was stuck in the same situation, a way out is to delay the execution of line where it reads from the file which is created during run time. 我遇到了同样的情况,一种方法是延迟从运行时创建的文件中读取的行的执行。 use this: 用这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM