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
- Settings.java
- 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?
2 Answers 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(..)
4 Comments
Settings.class.getResourceAsStream(..)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.