[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index] [Newsgroup Home]
[news.eclipse.newcomer] Re: Problem with finding a text file in Eclipse workspace

www wrote:
Eric Rizzo wrote:

And to get the text file to be on the classpath by default, store it in the source directory along with your Java code. Eclipse automatically copies non-Java files from the source directories to the build output, so they are on the runtime classpath by default.
Alternatively, you can create an additional source directory just for storing non-Java resources. That is actually the "clean" way to do it.


Hope this helps,
    Eric

Eric,

Thank you very much. You have hit the point that I am not clear about.

I already have found that my text file, temp.txt was automatically copied from the source folder (.../src/temp.txt) to the output folder ( .../bin/temp.txt). It was a shock to me. I am glad that you said it to me.

But, the problem remains:

BufferedReader inputStream = new BufferedReader(new FileReader("temp.txt"));

tells that the file temp.txt cannot be found. I get very confused and have spent a lot of time. I have tried Fresh, Project->Clean,.... Anything I can think of. But it still don't work. Even hard-coded the absolute path to temp.txt, Eclipse still cannot find it. So strange!

In the end, I gave up. I moved the file temp.txt to a folder outside of Eclipse workspace.

BufferedReader inputStream = new BufferedReader(new FileReader("absolute path to temp.txt"));

It works fine now.

Could you help me a little more? Thank you.

It is generally considered better practice to use Class.getResourceAsStream() which looks on the runtime classpath to locate the file. This is what Dave W. suggested earlier.
If you access a file directly (as with new FileReader() or new FileInputStream() or new File()) then Java will look in its current running directory (i.e., where the JVM was started from).
Your current running directory is set as the Project root by default, so Java doesn't know to look in your bin/ directory to find the file (unless you prefex the file name with "bin/" which I recommend against because it will break if you ever decide to move th file elsewhere).


Use of getResourceAsStream() will meet your needs nicely, unless you don't want to store the text file in the bin/ directory.

Hope this helps,
	Eric