How to write to a file in WebContent directory from a class in WEB-INF/classes directory

kamlesh tajpuri picture kamlesh tajpuri · May 30, 2013 · Viewed 16.8k times · Source

I have a Java Class UpdateStats in WEB-INF/Classes directory of a dynamic web application.This class has a function writeLog() which writes some logs to a text file.I want this text file to be in webcontent directory.Thus everytime the function is called updates stats are written in that text file. The problem is how to give the path of that text file in webcontent directory from within that function,which resides in WEB-INF/Classes directory.

Answer

Shinichi Kai picture Shinichi Kai · May 31, 2013

You can get your webapp root directory from ServletContext:

String path = getServletContext().getRealPath("WEB-INF/../");
File file = new File(path);
String fullPathToYourWebappRoot = file.getCanonicalPath();

Hope this helps.