Question

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.

Was it helpful?

Solution

You already have the file in file. Just replace

new FileReader(fileToBeRead)

by

new FileReader(file)

Or, even better, completely skip the unnecessary step of writing the file to disk and read the uploaded file stream immediately. Replace

File file = new File(destinationDir,item.getName());
item.write(file);
try {
    BufferedReader br = new BufferedReader(new FileReader(fileToBeRead));

by

try {
    BufferedReader br = new BufferedReader(new InputStreamReader(item.getInputStream()));

You may want to supply the charset as 2nd argument. I'd suggest UTF-8 for this.

OTHER TIPS

Adding to the responses above, hard coding file locations in Servlet code is not good practice because it usually causes the Servlet not to work when deployed on a different server or if the Web Application is run directly from a compressed WAR file. The correct method for reading a resource from a Web Application is by using either the getResource() or getResourceAsStream() methods. These two methods ensure the Servlet will always obtain access to the desired resource even if the Web Application is deployed on multiple servers or as a compressed WAR.

getResourceAsStream(java.lang.String path): The getResourceAsStream() method returns an instance of an InputStream to the physical resource of a Web Application. This method should be used when a resource needs to be read verbatim rather than processed by a Web Application.

getResource(java.lang.String path): The getResource() method returns a URL to the resource that is mapped to a specified path. This method should be used when a resource needs to be read as it would be displayed to a client.

Your code already contains the solution:

getServletContext().getRealPath(DESTINATION_DIR_PATH);

This is much better than:

String fileToBeRead = "C:/Program Files/Apache/Tomcat/...";

Another remark: Don't ever use new FileReader(), since you cannot specify the encoding that is used to convert the bytes of the file to the characters that you want. Use new InputStreamReader(is, encoding) instead.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top