简体   繁体   English

getResourceStream无法在Eclipse中加载新创建的文件

[英]getResourceStream unable to load newly created file in eclipse

I am creating a file dynamically using File IO , 我正在使用File IO动态创建文件,

FileOutputStream fos = new FileOutputStream("sample.txt"); FileOutputStream fos = new FileOutputStream(“ sample.txt”);

and trying to load sample.txt using getClass().getResourceAsStream("sample.txt") in another class, and it is unable to load the file, whereas if i refresh the project in eclipse ,it is able to load the file, does getResourceStream cache the files?, What i need is to create files dynamically and load them and perform some operations on them, Am I missing something? 并尝试在另一个类中使用getClass()。getResourceAsStream(“ sample.txt”)加载sample.txt,它无法加载文件,而如果我在eclipse中刷新项目,则可以加载文件, getResourceStream会缓存文件吗?,我需要动态创建文件并加载它们并对它们执行一些操作,我是否缺少某些东西?

Code InputStream is = getClass().getClassLoader().getResourceAsStream("sample.txt");//absolute path 代码InputStream是= getClass()。getClassLoader()。getResourceAsStream(“ sample.txt”); //绝对路径

PS :Added the newly created file in build path PS:在构建路径中添加了新创建的文件

When you run your app, you create that file in your source tree (usually /src). 运行应用程序时,您将在源代码树中创建该文件(通常是/ src)。 But your bin folder is what is on the classpath, (usually /bin). 但是您的bin文件夹是类路径(通常是/ bin)上的文件。 Because you create the file outside of eclipse (in another java process) it's only when you refresh your workspace that 1) it shows up in the source folder to eclipse and 2) then the builder copies it over to the bin folder. 因为您是在eclipse之外创建文件的(在另一个Java进程中),所以只有在刷新工作空间时,才1)将其显示在eclipse的源文件夹中,然后2)构建器将其复制到bin文件夹中。

getResourceAsStream( ) is meant to be used for something that is guaranteed to be on the classpath, a static resource in the source tree for example. getResourceAsStream( )用于保证在类路径上的东西,例如,源树中的静态资源。 For dynamically generated files, you need to find or pass in some other location and not use getResourceAsStream( ). 对于动态生成的文件,您需要查找或传递其他位置,而不要使用getResourceAsStream( )。

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

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