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...

RJ Balaji in as Vadacurry

Vadacurry is a perfect entertainment package – comedy, a romantic song, an item number, punch, villian, hero, noble cause – as we know, it is a masala movie. Movie revolves around lead male played by Jai and his immediate needs – getting Smart phone, the way he chooses to fullfill his need brings the neccesarily components to push the movie into vibration mode Director Saravana Rajan’s made the movie lighter enough to remove any sort of thrill from the movie, a team which has wide range of experience in providing laughter made this comedy-thriller into comdey-drama. The movie starts with RJ Balaji saying “my name is vadacurry, but I don’t have much to do here (ref. movie is titled as Vadacurry)”. Director gives Jai enough importance that almost any other character in the movie has little role to play, but when you leave the theater you know why its Vadacurry, without RJ Balaji movie might be rusty. Not a star cast unless you are going to consider Jei and Swathi as stars, whom I...

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...

The MFRP @ Best

The training that I experience here in Cognizant is good, after clearing all those modules I was waiting for the MFRP final review. At the first review our team was not able to perform well because we were not working as a team. It was more a single handed project, it was regarded as structured but not Object oriented programming by our Mentor these comments made us realize that we are struck deep and in dark. In the extension or the final phase of project we followed agile methodology in which I played as Business Analyst / Tester. Predominantly I was to be involved in resolving bug, code analysis and design, but nothing stopped me from helping in coding. I worked on bringing a program with BLOB data type that could handle all binary formats and a new theme/look for our project to make the interface look cool. I accomplished both the task on time with sincere guidance from Yusuf and Viswa (the two M.Tech grads in my batch with extensive practi...