2

I'm trying to write a file in dopost of servlet. I have a jsp file that send two variables to servlet in doPost method. and the servlet writes these variables in the file as follows:

 <form action="Client" method="POST">
  name <input type="text" size="20px" name="name1" ><br/> 
  name2 <input type="text" size="20px" name="name2"><br/> 
  <input type="submit" value="submit">
 </form>

My doPost is

String name1 = request.getParameter("name1");
String name2 = request.getParameter("name2");
BufferedWriter output = null;
try {
File doc = new File("/home/username/Desktop/file.txt");
            output = new BufferedWriter(new FileWriter(doc));
            output.write(name1+" "+name2);
            response.getWriter().append("File saved!");
        } catch ( IOException e ) {
            response.getWriter().append("Exception"+e.getMessage());

        } finally {
            if ( output != null ) output.close();
        }   

I created a war file and i put this war in my /var/lib/tomcat7/webapps/ after execution i got an exception

/home/username/Desktop/file.txt (Permission denied)

Why Permission denied issue is occuring ?

ksokol
  • 8,035
  • 3
  • 43
  • 56
Mehdi
  • 2,160
  • 6
  • 36
  • 53
  • 2
    You should write the file to a directory writeable by the user that runs Tomcat – Raffaele Feb 27 '16 at 09:35
  • waht do you mean ? i'm the user that runs Tomcat – Mehdi Feb 27 '16 at 09:37
  • You don't have sufficient permissions to write to that file. – Abdelhak Feb 27 '16 at 09:37
  • I give all permission chmod o+x to tomcat7 repository and to /home/username – Mehdi Feb 27 '16 at 09:37
  • Do you understand the difference between server side and client side in HTTP-based programming? It seems that you intend the program to write the file on the desktop of the user that runs it. But the user is on the client side, and the servlet is on the server side. – RealSkeptic Feb 27 '16 at 10:31

1 Answers1

-1

Try this:

String filename = getServletContext().getRealPath("/") + "filename.txt";
File file = new File(filename);

This will create a file names filename.txt in your webapps.context.

Sumeet Jain
  • 35
  • 2
  • 7