java - BufferedWriter doesn't throw any error, but file is blank -
i'm brand new using java web servers, , i'm writing basic application writes micro-posts file, later called , displayed. ( know database better this, assignment , using file-i/o keep things simple.)
here method in servlet receives form post , writes data file:
protected void dopost(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { string content = request.getparameter("postcontent"); calendar cal = new gregoriancalendar(); int day = cal.get(calendar.day_of_month); int month = cal.get(calendar.month) + 1; //add 1 because calendar class numbers months 0-11 int year = cal.get(calendar.year); int hour = cal.get(calendar.hour); int minutes = cal.get(calendar.minute); string datetime = integer.tostring(month) + "/" + integer.tostring(day) + "/" + integer.tostring(year) + " " + integer.tostring(hour) + ":" + integer.tostring(minutes); string user = request.getsession().getattribute("username").tostring(); servletcontext servletcontext = request.getsession().getservletcontext(); string path = servletcontext.getrealpath("/posts.txt"); //string path = getservletcontext().getrealpath("/posts.txt"); try { bufferedwriter writer = new bufferedwriter(new filewriter(path, true)); writer.write(user); writer.newline(); writer.write(datetime); writer.newline(); writer.write(content); writer.close(); }catch(ioexception ex){ system.out.println(ex.getmessage()); } response.sendredirect("listposts.jsp"); }
when run application, everthing goes smoothly , end redirected listpost.jsp
, file blank. i've looked @ other questions i'm doing everything right know of. setting bufferedwriter wrong? have posts.txt in wrong place? (it in webcontent folder).
thanks in advance.
update value of path
variable follows: /home/[myusername]/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/forum/posts.txt
update know can read posts.txt
, tells me application not having trouble finding it.
i'm reading file following code:
protected void doget(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { string path = getservletcontext().getrealpath("posts.txt"); bufferedreader reader = new bufferedreader(new filereader(path)); string username = reader.readline(); string datetime = reader.readline(); string postcontent = reader.readline(); reader.close(); request.setattribute("username", username); request.setattribute("datetime", datetime); request.setattribute("postcontent", postcontent); request.getrequestdispatcher("/listposts.jsp").forward(request, response);; }
ok, feel pretty foolish now. working along writing , reading file in directory of server, not source code stored. when checked text file had manually created, showed no change because not file being used. , input, sorry wasting time.
Comments
Post a Comment