private static final String DESTINATION_DIR_PATH ="/files";
private File destinationDir;
public void init(ServletConfig config) throws ServletException {
super.init(config);
String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
destinationDir = new File(realPath);
if(!destinationDir.isDirectory()) {
throw new ServletException(DESTINATION_DIR_PATH+" is not a directory");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println();
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory ();
fileItemFactory.setSizeThreshold(1*1024*1024);
//fileItemFactory.setRepository(tmpDir);
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if(item.isFormField()) {
out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
} else {
File file = new File(destinationDir,item.getName());
item.write(file);
String fileToBeRead = "C:/ProgramFiles/Apache/Tomcat/webapps/Readcsv/files/"+item.getName();
try {
BufferedReader br = new BufferedReader(new FileReader(fileToBeRead));..... and the code goes on..
I am using the above code for reading .csv file that is uploaded through a JSP form.
The code works perfectly fine.
But I want the code to be in a generic format since the above code is only working with a windows system and not the UNIX or any other OS.
String fileToBeRead = "C:/ProgramFiles/Apache/Tomcat/webapps/Readcsv/files/"+item.getName();
This particular line has to be changed for acheiving the task. Kindly let me know what can be done so that the code works fine in whatever OS it traverses. Also please point out all the areas which needs a change in the above code.
You already have the file in
file. Just replaceby
Or, even better, completely skip the unnecessary step of writing the file to disk and read the uploaded file stream immediately. Replace
by
You may want to supply the charset as 2nd argument. I’d suggest UTF-8 for this.