0

I have a Java project in eclipse and in my src folder I have a package called "instructions" and in that package I have the two files

  1. Settings.java
  2. Settings.txt

In Settings.java, I try to open Settings.text using

BufferedReader br = new BufferedReader(new FileReader("Settings.txt"));

but it says that the file is not found. What is the appropriate path to use?

asked Aug 7, 2011 at 15:09

2 Answers 2

2

You shouldn't use a FileReader. Use Class.getResourceAsStream():

FileReader needs an absolute path, or relative path to the user home folder. In addition to that, it will not load files that are within (jar) archives.

getResourceAsStream() looks in the classpath. The path can be relative to the current class, or absolute (starting from the root of the classpath)

Reader reader = 
 new InputStreamReader(getClass().getResourceAsStream("Settings.txt"), "UTF-8")
BufferedReader bufferedReader = new BufferedReader(reader);

(In case the method is static, you can call use the class literal - YourClass.class.getResourceAsStream(..)

answered Aug 7, 2011 at 15:11
Sign up to request clarification or add additional context in comments.

4 Comments

I did this: BufferedReader br = new BufferedReader(getClass().getResourceAsStream("Settings.txt")); and it's giving errors
but this is in a static method and getClass() is causing an error
if it is a static method, then use Settings.class.getResourceAsStream(..)
Its also important that when/if you bundle and distribute this app that the resource is included in the JAR. Typically resources are placed in their own folder (package) separate from the classes that use them.
0

You should either set the path to this folder, or move the file to your project directory. The default path of eclipse is not your source file folder but the project folder.

answered Aug 7, 2011 at 15:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.