The FileNotFoundException
error you are getting is not from this line:
new File(this.getClass().getResource("/http/templates/404.html").getFile())
It appears that after you are storing these File
objects in hash map, you are trying to read the file (or serve the file by reading using FileInputStream
or related APIs). It would have been more useful if you had given the stack trace and the code which is actually throwing this exception.
But the point is that files present within the JAR files are not the same as files on disk. In particular, a File
object represents an abstract path name on disk and all standard libraries using File
object assume that it is accessible. So /a/path/like/this
is a valid abstract path name, but file:/Users/Kelly/Desktop/Java_HTTP_Server/build/jar/server.jar!/http/templates/404.html
is not. This is exactly what you get when you call getResource("/http/templates/404.html").getFile()
. It just returns a string representing something that doesn't exist as a file on disk.
There are two ways you can serve resources from class path directly:
- Directly return the stream as a response to the request.
this.getClass().getResourceAsStream()
will return you theInputStream
object which you can then return to the caller. This will require you to store anInputStream
object in your hash map instead of a file. You can have two hash maps one for files from class path and one for files on disk. - Extract all the templates (possibly on first access) to a temporary location say
/tmp
and then store theFile
object representing the newly extracted file.