Writing to a File from a Servlet in a Java EE Web Application

We will see how to write to a file in file system from a servlet. To write to a file in the root folder of a web app, we will need the real path to it. Using the path we can write to the file. Note that the WeContent folder you see in eclipse during development becomes the root folder of the web app, as we archive the contents of the WebContent folder to create a war file.  You can find more details on war creation and deployement @ packaging-and-deploying-a-web-application-into-standalone-apache-tomcat.

This note was prepared in response to a questen asked by a Java EE user through the facebook page. Original question from Java EE user is as follows: "i want to add new node to an existent xml file that is in the webcontent but changes are made in a temporary file <while running from eclipse> and when i restart tomcat all the changes are gone. So how to save this changes after deployment ?"

 

Step 1: Finding the real file path of root folder

First, we will look at three file path methods of the File class.

  • getAbsolutePath() - returns the absolute pathname string of this abstract pathname.

  • getCanonicalPath() - returns the canonical pathname string of this abstract pathname.

  • getPath() - converts this abstract pathname into a pathname string.

 

We can create a file instance within my Servlet as:

File file = new File(“test”);

 

What will getAbsolutePath(),getCanonicalPath() and getPath() print if I run the servlet from within eclipse?

  • getAbsolutePath() printed D:\eclipse-juno\test

  • getCanonicalPath() printed D:\eclipse-juno\test

  • getPath() printed test

Where D:\eclipse-juno is the folder where eclipse is installed

 

Now deploy the same project to a standalone tomcat and execute the same URL you see in eclipse browser, from a standard browser like chrome or firefox. This time you stop the server started from eclipse and start the tomcat server running startup.bat by going to the bin folder of tomcat installation.

What will getAbsolutePath(),getCanonicalPath() and getPath() print this time?

  • getAbsolutePath() printed D:\apache-tomcat-7.0.33\bin\test

  • getCanonicalPath() printed D:\apache-tomcat-7.0.33\bin\test

  • getPath() printed test

 

Now stop the server, go one directory back to D:\apache-tomcat-7.0.33 through command line and run startup.bat as bin\startup.bat. What will getAbsolutePath(),getCanonicalPath() and getPath() print if I run the servlet after starting tomcat from command line?

  • getAbsolutePath() printed D:\apache-tomcat-7.0.33\test

  • getCanonicalPath() printed D:\apache-tomcat-7.0.33\test

  • getPath() printed test

 

Note that the path changes from execution to execution based on from where the server was started.

What if I want to write to a file within the WebContent directory in eclipse which will be the project root folder (e.g. DynaServletProject)?

Now try ServletContext().getContextPath() and ServletContext().getRealPath:

  • getServletContext().getContextPath();

  • getServletContext().getRealPath("/");

  • getServletContext().getRealPath("/WEB-INF");

Below are the respective values when I ran the servlet within eclipse:

getServletContext().getContextPath() 
/DynaServletProject

getServletContext().getRealPath("/")
D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\DynaServletProject\

getServletContext().getRealPath("/WEB-INF")
D:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\DynaServletProject\WEB-INF

 

Below are the respective values when I ran the servlet from standalone Apache Tomcat:

getServletContext().getContextPath()
/DynaServletProject

getServletContext().getRealPath("/")
D:\apache-tomcat-7.0.33\webapps\DynaServletProject\

getServletContext().getRealPath("/WEB-INF")
D:\apache-tomcat-7.0.33\webapps\DynaServletProject\WEB-INF

We can use getRealPath("/") to get the real path to the root folder.

 

Step 2: Writing to a file inside WebContent/Root folder from a servlet

Put the below code within the get method of servlet and run the servlet on server:

String contextPath = getServletContext().getRealPath("/");

String xmlFilePath=contextPath+"\\test";

System.out.println(xmlFilePath);

File myfile = new File(xmlFilePath);

myfile.createNewFile();

When run from within a standalone Apache Tomcat, this will create a file test in the root folder. Though the root folder is same as the WebContent folder, as you can see from above examples, the method getServletContext().getRealPath doesn’t point to the WebContent folder (root) when run from within eclipse. Instead it write to a temporary location. However, once you deploy your application to the Apache Tomcat servlet container everything will work as expected and file will be created in the root folder of the webapp.

Quick Notes Finder Tags

Activities (1) advanced java (1) agile (3) App Servers (6) archived notes (2) Arrays (1) Best Practices (12) Best Practices (Design) (3) Best Practices (Java) (7) Best Practices (Java EE) (1) BigData (3) Chars & Encodings (6) coding problems (2) Collections (15) contests (3) Core Java (All) (55) course plan (2) Database (12) Design patterns (8) dev tools (3) downloads (2) eclipse (9) Essentials (1) examples (14) Exception (1) Exceptions (4) Exercise (1) exercises (6) Getting Started (18) Groovy (2) hadoop (4) hibernate (77) hibernate interview questions (6) History (1) Hot book (5) http monitoring (2) Inheritance (4) intellij (1) java 8 notes (4) Java 9 (1) Java Concepts (7) Java Core (9) java ee exercises (1) java ee interview questions (2) Java Elements (16) Java Environment (1) Java Features (4) java interview points (4) java interview questions (4) javajee initiatives (1) javajee thoughts (3) Java Performance (6) Java Programmer 1 (11) Java Programmer 2 (7) Javascript Frameworks (1) Java SE Professional (1) JPA 1 - Module (6) JPA 1 - Modules (1) JSP (1) Legacy Java (1) linked list (3) maven (1) Multithreading (16) NFR (1) No SQL (1) Object Oriented (9) OCPJP (4) OCPWCD (1) OOAD (3) Operators (4) Overloading (2) Overriding (2) Overviews (1) policies (1) programming (1) Quartz Scheduler (1) Quizzes (17) RabbitMQ (1) references (2) restful web service (3) Searching (1) security (10) Servlets (8) Servlets and JSP (31) Site Usage Guidelines (1) Sorting (1) source code management (1) spring (4) spring boot (3) Spring Examples (1) Spring Features (1) spring jpa (1) Stack (1) Streams & IO (3) Strings (11) SW Developer Tools (2) testing (1) troubleshooting (1) user interface (1) vxml (8) web services (1) Web Technologies (1) Web Technology Books (1) youtube (1)