Skip to main content

How to: Write a file inside webapp directory of Tomcat with Struts2 or JSP & Servlet





Hi! This time its for struts break for database, ever felt you wanna store files temporarly inside your server directory? then this post is to help you out if you are new to java and you have interest in learning, this is good to know! trust me even big folks won’t know this I’m going to tell for Struts2 framework.

============================================

Using ServletContext & ServletActionContext in Struts2

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

============================================

public String execute() {

try {

String path = “/folder1/file1.txt” ;

System.out.println(“where it might write ”

+ System.getProperty(“user.dir”));

ServletContext context = ServletActionContext.getServletContext(); //Line No.6

path = context.getRealPath(path);

File file = new File(path);

// if file doesnt exists, then create it

if (!file.exists()) {

System.out.println(“trying to creat new file at ” + path);

// Getting parent directory then creating it

File parent = file.getParentFile();

parent.mkdirs();

// Creating file

file.createNewFile();

}


FileWriter fw = new FileWriter(file);

BufferedWriter bw = new BufferedWriter(fw);

bw.write(“This is Written to file”);

System.out.println(“Where it wrote ” + file.getAbsolutePath());

bw.close();

System.out.println(“Done”);

return “success”;

} catch (IOException e) {

e.printStackTrace();

return “input”;

}

}

“String pathname = context.getRealPath(filename);” is the trick here. getRealPath(fielpath) return the exact path corresponding to the server. I said right even experienced folks dont know, cause this is not goot practice :oh!no: if the server is unpacket getRealPath() will return null!! so the best was is to return as String and handle it in JSP or whatever way to can. Anyway Server will be unpacked by default but if something screw up!  Ok TC keep thinking.


For Jsp & Servlet replace line no. 6 with *ServletContext context = this.getServletContext();* Class must extend HttpServlet and init(config) must have the call super.init(config) else context will be null.


Comments

Popular this month

Puththu kovilum Putho tilesum, as they are built

Its the grand Aadi season here in Tamil Nadu wherever you go you'd be followed by awful noise from no mercy speakers masqueraded as a devotional song. Yes, this is the first post dedicated to it. Hindu is not a religion but it's idealism, a way to unite people, that's perfectly constructed by assuming separate task to every God, no single God worship. Hindus moved from nature worship to idol worship, but that doesn't mean that we don't have nature worship we have created an idol for them and continued to worship them in a different form. Snake is a beautiful reptile, I have made friend with few too... Our ancestor found the natural law, 'every living creature on earth is important for the ecosystem to be balanced'. Maybe to make sure snakes are not killed fearing their venom they made them as God too! Not just idol snakes, they are worshipped as they are at their  conquered (from rats and termite)   nest or  puthu . Puthu...

Up and Close with Sudalai Madan: The Encounter

Night of 13th April all the preparations for the rituals were done in the temple, Sudalaimadan swamy was decorated with flowers, fruits and coconuts; the dedications reached above his chest. My cousin Sudalai Muthu, senior priest of the shrine reached home by late-night got blessings of his father Late Shanmugam Sundaram also previous head priest and blessed the family members in room dedicated for God, then started towards the temple. People have already gathered in huge numbers and were waiting for the Sudalaimada Swamy's arrival at Temple. Different rituals were offered by people to the Lord in order to get the blessings. As it is believed Sudaimada Swamy, the son of Lord Siva used to consume meat in Kailash for this reason he is sent to earth, where he can satisfy his earthy hunger thereby not polluting Kailash. Sree Aaladi Padmanabha Sudalaimada Swamy Temple, Kumarapuram Offering meat to Sudalaimadan is the most important and watchful event of the festival. Many devotees off...

why do people sweat more in chennai???

One of the famous ornament of chennai is its summer!. Everyone here would have at least once talked about its effect and the way they affected. People comes out with sweats flowing from the body is the usual scene of chennai noon. The sweat produced is not just due to the temperature of the region. It is in fact due to the high humidity of chennai. To explain this lets see a fact, people in chennai sweats more than the people in delhi where the temperature is higher than the former. This is because of chennai's location. Chennai is located near sea due to which sea water evaporation is high during summer which in turn increases the humidity (Amount of water vapour present in air). Normally human blood temperature is about 35 deg Celsius. If the outside temperature is more than that, then our system tries to automatically cools down by releasing sweat from the body. The sweat which is released cools the surrounding heat by converting into vapour thereby reducing the body te...

Old is Gold: Vaitheeswaran Koil

My parent’s Shastiapthapoorthi just happened on 8th Oct at Thirukadaiyur, Amritaghateswarar – Abirami Temple , we were so glad that all poojai took place on Nandhi mandapam. My scheduled next stop was my uncle home for virunthu . But after getting boosted with abundant spiritual aura can’t stop myself from stopping for Vaitheeswaran koil on the way, that evening along with my wife experienced the glory of good old times.   Though Vaithyanatha swamy(Lord Shiva as Lingam) is the prime deity, Muthukumaraswamy stole the day, the panchaloga figurine of Lord Murugan in the shrine. Its Urchavar as its referred here since the figure is movable and comes out of the mandapam on special occasions. We went inside temple purified ourselves with holy water in temple pond, worshiped goddess Thaiyal Nayagi then stood in front of Lord Shiva for a very long time, but no poojari-iyer dropped by I’m not sure what special occasion it is on 08-Oct-13, as we saw many move towards closed doors of parti...

How to: SCJP / OCJP certification, best practice, chennai

Oracle Certified Professional, Java Programmer(OCP,JP) is the certification I’m gonna discuss in this post. This certification is offered by ORACLE prior to this Sun was offering it in the name SCJP, in a generic way I’m gonna refer this as OCJP. Here I have given a list of FAQs that you can use. 1. What are the prerequisites or Should I have completed any other exam before this? A: Not required. But it is good that you take mock exams available in various sites before facing the big challenge. You’ll face 60 questions within 150mins you have to answer them and score 61% to clear the exam (37 questions must be correct). 2. What is the best book for this exam? A: I haven’t heard of a book for OCP,JP 1Z0-851 but there is book for SCJP 310-065 which is essentially the same exam but the name was changed once Oracle started to offer the exam. The book is authored by peoples who prepares the examination papers and patterns so they would be the best guide. 3. Is book enough for ...