Thursday, March 7, 2013

File not found issue with tomcat: URL Encoding

I have to admit, today was lot better than yesterday. My struggle started when I was asked to quickly ( I mean it, in 10 minutes or so..) deploy a POC application on amazon ec2 instance. It is a windows 2008 server, so installed tomcat as service under "Program Files" and installed java 7. Hoping my 5 pages application will fly in no time that's when I noticed an error stack on the tomcat console :(. Main root cause was:

"Caused by: java.io.FileNotFoundException: File 'C:\Program%20Files\apache-tomcat-7.0.29\webapps\xyz\WEB-INF\classes\createData.sql' does not exist"

I could see the file under WEB-INF\classes and that's when I realized that my URL is getting encoded, hence all spaces are getting replaced with %20.

I had below line of code which was causing the issues since there is no folder with name "Program%20Files" in the system.

String path = FileUtils.class.getClassLoader().getResource("createData.sql").getPath();
List readLines = FileUtils.readLines(new File(path));
I wrapped it using URI and BOOM problem went away.

String path = FileUtils.class.getClassLoader().getResource("createData.sql").getPath();
List readLines = FileUtils.readLines(new File(new URI(path).getPath()));

as usual I happy soul again.
Manisha