问题
I have a Web Project where I am using the following code:
try {
br1 = new BufferedReader(new FileReader("queryWords.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Now for this, it is throwing me the following exception:
java.io.FileNotFoundException: queryWords.txt (The system cannot find the file specified)
(I am storing 'queryWords.txt' file in the Project Folder itself)
When I change my code to the following:
br1 = new BufferedReader(new FileReader("C://Users//Project//Demo//queryWords.txt"));
where I have given the full absolute path, it runs perfectly but when I change my project to a plane 'Java Project', the initial code works perfectly fine and I am not getting any exception.
So why this unexpected behavior is happening? When my project is just 'Java Project', I don't have to provide the full path but when I have the 'Dynamic Web Project', I am getting the error if I don't give the full absolute path of the file.
Note:I am using Eclipse IDE.
回答1:
"When my project is just 'Java Project' I don't have to provide the full path"
Your IDE is reading the file from working directory which is normally the project root.
"when I have the 'Dynamic Web Project', I am getting the error if I don't give the full absolute path of the file"
Web application are packaged in to a .war(.jar). Once the application is built, the files in the src are included into the class path, and should be read as such. In your case, your file was never included into the jar, as it's not a resource within the src. Even though reading the file from the file system might work on your system, no one else using the application will be able to read it.
Instead you should have your resources in the src, say a resources
package. It depends on the structure of your build, what path you should provide, but I think with a normal maven project structure (with the file in the src/main/resources/myfile.txt) and a regular java project structure (src/resources/myfile.txt) you are safe to use the following
InputStream is = getClass().getResourceAsStream("/resources/myfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
来源:https://stackoverflow.com/questions/23182968/getting-filenotfoundexception