• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to pass text to file using Jsp?

 
Neelima Paramsetty
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
i want to send some data into the file.for that the code is
<html>
<body>Action completed
<%@ page import ="java.io.*" %>
<%! String str="neelima"; %>
<%
try
{

PrintWriter out=new PrintWriter(new FileOutputStream("\jspex.txt"));
out.println(str);
out.close();
}
catch(Exception e)
{
e.getMessage();
}
%>
</body>
</html>
jspex.txt file is inthe same path as this jsp page.how i have to set the path for this text file.
anybody can help me to solve this.
Thanks in advance,
Neelima
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Three problems here:
- You cannot declare a variable called "out", because the JSP environment already has an implicit variable by that name (which is a JspWriter)
- You have a \ character at the beginning of your filename, which must be removed
- You need to call the ServletContext's getRealPath() method to obtain a path to the file you want to write.
Here's a revised version:
 
Ron Newman
Ranch Hand
Posts: 1056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Other things to think about:
FileWriter is better than FileOutputStream if you are writing character data
If you want to append to the file instead of overwriting it each time, then construct your FileWriter object with FileWriter(realPath, true)
If you're going to write a lot of data, consider using a BufferedWriter
 
Neelima Paramsetty
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi newman,
thanks a lot.it is working nicely.
thanks,
neelima
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic