The method ServletContext.getResourceAsStream() allows you to load a resource (a file in your case) as a Stream. I suggest placing the file, regardless of format, in the WEB-INF directory right along side of the web.xml file. If the file's name is additional.xml, you would have a line of code that reads In the above, sc is the current ServletContext. The file can be of anytype (.txt, .properties, .xml), you just have to use the InputStream to read it's contents.
Hello Ken: You only can to accede to ServletConfig object from within a servlet (I suppose). My question is: How can you write to a text file from one class that no implements HttpServlet?. I have a class named "EventWriter" with a method named "addEvent". This class no implements HttpServlet. I want to maintain updated a file named "event.log" (I would like to put it in /Web-inf path). How can i do it? This is my class:
First, I would suggest NOT putting a file generated by your app in the WEB-INF directory. This directory's purpose is to allow the web app/container access to files needed for configuration while keeping them off limits for incoming web request. Keep in mind, if you deploy a .war file and the container does not unpack the .war, you may get an error when writing to that directory. Remember, the method name is getResourceAsStream. There is not createResourceAsStream type method. I'd suggest setting a Context Parameter as the file location and creating is somewhere on the disk not within the public HTML directory of the server you are using. A ServletContext object is just an object. Any class you write can take a reference to it in it's constructor or method calls. Simply pass it in as a init parameter to your object or as an arguement in a method call.