Currently I'm in need of reading txt file from a folder structure by java program in eclipse, but always I get to have Null as result when to use getResourceAsStream(). I've tested all possible combination of relative paths. I've read more problem similar to this, but none helped me to solve the problem.
Kindly suggest me regarding this issue. The following is my folder structure.
Relative paths are extremely dangerous unless you are 100% certain what those paths are relative to. And for things like webapps and general puttering around in IDEs or other container environments, that point may change at unpredictable times.
In any event, getResourceAsStream() is used to obtain data from an app's classpath, not its relative directory, and your example directory structure has the resource in the SOURCE tree, not the CLASS tree.
Loudly announcing something is true and finding out you're wrong makes you feel foolish.
Finding out you're wrong and refusing to admit it makes you LOOK foolish.
The base directory for a relative path in Eclipse is, I believe, the directory containing the eclipse executable! You can easily verify this by creating a File with location "." and then printing out its absolute path. Tim is 100% correct - you should really be getting the file as a resource.
Either that, or using a system property to define the location of the file (or the base directory of a set of files) and then using that along with the relative path to open the file. This pattern is used often in Java EE apps when the static files being server are external to the web application and are not convenient to package with the web application (mainly because you don't know what files there will be because the list of file changes dynamically).
Thanks for your valuable points here. But I'm not able to read the file as resource stream. I tried all combinations of URI, but none helped me. Kindly suggest me with sample code. My package structure is same as I mentioned before since resource folder and don't like to place this file into src folder of current java program package. (its actually xml file to read)
No pain, No gain.
OCJP 1.6, Liferay Certified Developer 6.1
Where does your class file end up after it is compiled? The contents of the resource directory should go into the same location. For example, if I was working on this project I would change it to use a Maven directory structure:
Then in Core.java, I would have getResourceAsStream("myText.txt"). The getResourceAsStream method assume the classpath os the base directory, all file locations are relative to the classpath (or actually, relative to individual paths listed in the classpath)