Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to write a file while using Tomcat

Tags:

java

tomcat

I am unable to create and then write a file in Tomcat. The file gets created if I run the java program (only the writing piece of code) as a Java application, but fails in Tomcat.

there is no error message. The file is simply not created at all!

Please suggest if I am missing something here:

//code inside the servlet
public void setData(HttpServletRequest request){
    name=request.getParameter("name");
    address=request.getParameter("address");


    BufferedWriter dataOut;
    try {
        System.out.println("Wrinting file...");
        dataOut = new BufferedWriter(new FileWriter("data.txt", true));




        dataOut.write("name:");
        dataOut.flush();

        dataOut.write("address");
        dataOut.flush();

        dataOut.write("\n");
        dataOut.flush();

        dataOut.close();
        System.out.println("File write complete!");
    }
    catch(Exception e){
        e.printStackTrace();
    }
like image 497
Rookie Avatar asked Apr 14 '13 06:04

Rookie


People also ask

What is webapps folder in Tomcat?

The webapps directory is where deployed applications reside in Tomcat. The webapps directory is the default deployment location, but this can be configured with the appBase attribute on the <Host> element.

Why is my Tomcat not starting?

Most common issue with Tomcat note starting is that Java is not configured properly, user trying to start Tomcat does not have permissions to do so, or another program is using port 8080 on that server.


2 Answers

Looks like the file really is created without problems.

You may actually be missing where it is saved.

Change this line:

System.out.println("File write complete!");

To:

System.out.println("File write complete! Saved to: "+new File("data.txt").getAbsolutePath());

And you may solve the mistery.

like image 170
acdcjunior Avatar answered Nov 05 '22 04:11

acdcjunior


The file is being created, but it is using a relative path. It will be created relative to the execution location, which on Tomcat will not be where you're used to it being.

Use an absolute path or print its location.

like image 3
Ray Stojonic Avatar answered Nov 05 '22 06:11

Ray Stojonic