Sauda��es Javanesas L�o
Servlet Para Escrever em arquivo
/**
* This is a simple servlet that just writes some information
* to a text file. This is a real servlet that is used on this site
* to let people request information for the Harrisburg Area
* Java Users Group. It writes the info that they input to a file
* I am extending this to send me an e-mail to let me know that someone
* has requested information. Actually I got the idea for the e-mail
* from Alan Williamson's great book:
* Java Database Development JDBC & Servlets
* (ISBN 0-13-737917-x)
*@author - Jon M Strande [EMAIL PROTECTED]
*@date 5/26/98
*/
//import the classes we need
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import sun.servlet.http.*;
import sun.misc.*;
import java.util.*;
public class HJUGRequest extends HttpServlet
{
private String _baseDir;
/**
*/
public void init (ServletConfig config) throws ServletException
{
super.init(config);
_baseDir = "/temp";
}
/**
*/
public void service (HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException
{
//get a PrintWriter & FileWriter to write to the results
file
PrintWriter printWriter = null;
FileWriter results = null;
//getParameterNames gets the name value pairs
//from the form that the user entered information on
// and stores it in an enumeration
Enumeration values = request.getParameterNames();
//get an output stream to send content back to the user
PrintStream out = new PrintStream
(response.getOutputStream());
//survey name is one of the parameters, it is a hidden
field
String surveyName = request.getParameter ("survey");
String cookieHeader = request.getHeader ("Cookie");
//set the content type we will send back to the browser
response.setContentType ("text/html");
try
{
results = new FileWriter (_baseDir +
System.getProperty
("file.separator") + surveyName + ".txt", true);
printWriter = new PrintWriter (results);
printWriter.println ("");
while ( values.hasMoreElements() )
{
String name, value;
name = (String)values.nextElement();
value = request.getParameter (name);
if ( name.compareTo ("submit") != 0 )
{
printWriter.println (name + ": " + value);
}
}
printWriter.println ("");
//lets thank the user
out.println ("Thank-You for your request<br>");
out.println("You will be contacted shortly
by:<br>");
out.println("<A
HREF=\"mailto:[EMAIL PROTECTED]\">Jon Strande</A>");
}
catch (IOException e)
{
e.printStackTrace();
out.println ("A problem occured while recording your
answers. Please try again.");
}
try
{
if ( results != null )
{
results.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
out.close();
response.getOutputStream().close();
}
}
E agora o Servlet para ler os dados de um arquivo...
/*
* A simple servlet that reads a text file then sends the content
* to a client/browser. The possibilities are limitless!!!
*@date 6/2/98
*@author Jon M Strande - [EMAIL PROTECTED]
*/
//lets import the classes that we need.
import java.io.*;
import java.util.Vector;
import javax.servlet.*;
import javax.servlet.http.*;
public class ReadFileServlet extends HttpServlet
{
//this is the directory where the file resides
private String _baseDir;
//I am just going to store the lines of the file in a vector
//maybe not the best way to do this, but it works easily.
private Vector v = new Vector();
public void init (ServletConfig config) throws ServletException
{
super.init(config);
_baseDir = "/temp";
}
public void doGet (HttpServletRequest req, HttpServletResponse
res)
throws ServletException, IOException
{
//getOutputStream is in the Interface
javax.servlet.Servlet.ServletResponse
//It provides an output stream for returning data to the
user
ServletOutputStream out =
res.getOutputStream();
// set content type and other response header fields
first
//this is also in the interface
javax.servlet.Servlet.ServletResponse
res.setContentType("text/html");
//set the title stuff of the page
//println is a Method in the Class
javax.servlet.Servlet.ServletOutputStream
//it is an abstract class
//println - Prints the string provided, followed by a
CRLF.
out.println("<HTML><HEAD><TITLE> SimpleServlet
Output </TITLE></HEAD><BODY><FONT FACE=\"Verdana, Arial,
Helvetica\">");
out.println("<h1> ReadFileServlet Output </h1>");
out.println("<br>Output:");
try
{
String fileLine;
//you could pass the filename to the servlet as
a parameter.
String InputFile = "/temp/Survey01Results.txt";
// Get the file specified by InputFile
BufferedReader br = new BufferedReader(new
InputStreamReader(new
FileInputStream(InputFile)));
//while there are still lines in the file,
get-em.
while((fileLine = br.readLine())!= null)
{
//add each line to the vector, each line
will have a CRLF
v.addElement(fileLine);
}
//IMPORTANT!!!! - CLOSE THE STREAM!!!!!
br.close();
}
catch(IOException e)
{
out.println("An error occurred reading the file"
+ e);
}
//Here we will just loop through the vector and print
the
//lines of the file out to the client.
int num = v.size();
for(int times = 0; times < num; times++)
{
//maybe you want to check the value or do some
//processing to the text before sending it out.
//if so, you could say;
//String s;
//s = v.elementAt(times).toString());
//s = doSomething(s);
//out.println(s);
out.println(v.elementAt(times).toString());
out.println("<BR>");
}
out.println("<BR><P>This is output from
<b>ReadFileServlet</b>.</font>");
out.println("</BODY></html>");
//close the Servlet outputstream
out.close();
}
public String getServletInfo()
{
return "A Servlet that prints the contents of a file to
the user.";
}
}
Para saber mais visite: http://www.servletsource.com/
Espero ter ajudado.
[]'s
Handerson F. Gomes
Leo wrote:
>
> Ola pessoal,
>
> Algu�m tem algum exemplo de leitura/grava��o de arquivos de texto utilizando
>servlets ???
>
> Estejam a vontade para me enviar um e-mail...
>
> grato pela aten��o.
>
> Paz e Felidade para todos.
>
> * Para nao receber mais e-mails da lista, acesse
<http://www.sun.com.br:8080/guest/RemoteAvailableLists>, coloque seu
e-mail, escolha a lista <[EMAIL PROTECTED]> e de um <submit>.
--
**********************************************************
Handerson Ferreira Gomes, Analista de Sistemas
CITS - Centro Internacional de Tecnologia de Software
Depto: CNTS - Centro de Novas Tecnologias de Software
Parque de Software de Curitiba
81230-000 Curitiba, PR, Brasil
+55 41 317 2086, fax: 337 1002
http://www.cits.br
**********************************************************
* Para nao receber mais e-mails da lista, acesse
<http://www.sun.com.br:8080/guest/RemoteAvailableLists>, coloque seu e-mail, escolha a
lista <[EMAIL PROTECTED]> e de um <submit>.