FileReader
I'm trying to read a file. I get the file-url from a relative path.
The code I am using looks like this:
URL config = getClass().getResource("/../../install/db.sql");
FileReader ir =new FileReader(config.getFile());
When I debug the script, config.getFile() contains:
"/D:/Barts%20docs/MCT/ProjectProgWeb4/web/devzone/forum/build/web/WEB-INF/config.xml"
This is a correct path to the file.
Although, the script crashes at:
FileReader ir = new FileReader(config.getFile());
What am I doing wrong?
What error message does it show you?
How do you ask for "/install/db.sql", and get "WEB-INF/config.xml"?
An alternative to the Class.getResource() call is to use the ServletContext methods: getRealPath or getResourceAsStream.
application.getRealPath("/WEB-INF/config.xml") turns a website relative path into a real location on disk (so you can use it with the File constructor)
application.getResourceAsStream("/WEB-INF/config.xml") is similar, but returns an InputStream of the contents.
If you only want to read a file, the getResourceAsStream() method is preferred, as it will work even if the web-app is bundled in a WAR, and not "exploded"
getRealPath() would return a path to a file within a WAR, which the File constructor can't handle.
Hope this helps,
evnafets
whoops.. I made a mistake, pasted the wrong string into this topic:
config.getFile() contains:
"/D:/Barts%20docs/MCT/ProjectProgWeb4/web/devzone/forum/build/web/install/db.sql" instead of what I wrote before.
This path is the correct path to the file.
Thanks for the answer evnafets, but I am not able to use getRealPath and getResourceAsStream because I try to read the file inside a 'data accessor'-class.
In the data-accessor class I don't seem to be able to use ServletContext methods. :(
I found the solution:
URL databaseURL = getClass().getResource("/../../install/db.sql");
String databasefile = databaseURL.getFile();
databasefile = databasefile.replaceAll("%20", " ");
FileReader ir = new FileReader(databasefile);
Explanation:
getClass().getResource("/../../install/db.sql") returned the correct path to the file, but the spaces in the path were replaced with "%20".
The FileReader seems not to be able to read a path with "%20" in it, so I solved the problem by replacing all "%20" with " ".