简体   繁体   中英

Permission denied issue while writing file using servlets

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 ?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM