Sunday, April 7, 2013

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.