I am trying to read a file in a servlet. I am using eclipse IDE.
I get a FileNotFoundException if I provide relative file name.
List<String> ls=new ArrayList<String>();
Scanner input = new Scanner(new File("Input.txt"));
while(input.hasNextLine()) {
ls.add(input.nextLine());
}
The same code works if I put the absolute path like this:
Scanner input = new Scanner(new File("F:/Spring and other stuff/AjaxDemo/src/com/pdd/ajax/Input.txt"));
The Java file and text file are there in the same folder.
Does it searches text file in some other folder ?
Setting the Working Directory
One option you have when working inside of Eclipse is to set the working directory in your launch configuration. To do this:
Run|Run Configurations…ArgumentstabWorking directorysectionOtherYou can validate this in a test by printing:
This has the benefit of not changing your code for production vs. test.
Recommendation
However, the best approach is to always be explicit about the working directory by way of configuration. This puts the working directory under the direct control of your application and away from tools and servlet containers such as Eclipse and Tomcat. To do this, you would use the following
Fileconstructor