A servlet class handles the incoming request object, fetch data & store into StringBuilder/StringBuffer and passes the data to another class to write into a file.
ActionClass
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
String fileName = request.getparameter("fileName");
String body = request.getParameter("innerHTML");
String head = request.getParameter("headContents");
StringBuilder sbr = new StringBuilder();
sbr.append(body); sbr.append(head);
OR
StringBuffer sbf = new StringBuffer();
sbf.append(body); sbf.append(head);
FileWrite fw = new FileWrite(fileName, sbf/sbr); /* write the data into file*/
}
FileWrite
class FileWrite{
public FileWrite(String fileName, StringBuilder sbf){
boolean isExist = checkFileName(fileName); /* return true or false */
if(isExist){
String name = reName(fileName); /* rename & return new name */
/* write the file in new file */
}else{ /* write in same file name */ }
}
public String reName(String oldName){
/* rename oldName as newName & checks via isExist(newName) */
}
public boolean isExist(String filename) {
// checks the file in directory, if found already
return true;
else return false;
}
}
as you can see in above example, action class passes the data to FileWrite class which writes the data to a new file. there are hundreds of client might sent the request at same time to store the data in new file.
so my question is, in servlet class what should i use to store the data. is it String or stringBuffer or StringBuilder?? is it issue of thread safe?
Yes, you should care about thread safety issues, but the issue with thread safety isn’t in your choice of String or stringBuffer or StringBuilder.
Where you need to watch out (potentially) for thread safety is if you get two requests for the same filename to your FileWriter class.
Also, I would note that it is quite dangerous from a security standpoint to simply take raw file locations directly from a get parameter – as users can overwrite other user files, or (potentially, depending on permissions) even OS files.