Example: servlet reads file contents and prints output on page

Source: Internet
Author: User

1  PackageCOM.MHB;2 3 ImportJava.io.BufferedReader;4 ImportJava.io.File;5 ImportJava.io.FileReader;6 Importjava.io.IOException;7 ImportJava.io.PrintWriter;8 9 Importjavax.servlet.ServletException;Ten ImportJavax.servlet.http.HttpServlet; One Importjavax.servlet.http.HttpServletRequest; A ImportJavax.servlet.http.HttpServletResponse; -  -  Public classFileReadextendsHttpServlet { the  -  Public voidInit ()throwsservletexception { - } -  +  Public voiddoget (httpservletrequest request, httpservletresponse response) - throwsservletexception, IOException { +Response.setcontenttype ("text/html");//Format Response Content AResponse.setcharacterencoding ("gb2312");//Setting the response content encoding atPrintWriter out = Response.getwriter ();//Get Out Object -String fileName = "Content.txt";//Specify file name -String Realpath =Request.getrealpath (fileName); -  -File File =NewFile (realpath); -  in if(File.exists ()) { -FileReader reader =NewFileReader (file);//Get input stream toBufferedReader Bufferreader =NewBufferedReader (reader);//using buffered streams +String line =NULL;//each row of data -  while(line = Bufferreader.readline ())! =NULL){//Loop Read theOut.print (line + "<br/>");//Output File Contents * } $}Else{Panax NotoginsengOut.print ("file does not exist!) "); - } the  + } A  the  Public voidDoPost (httpservletrequest request, httpservletresponse response) + throwsservletexception, IOException { - } $  $  Public voiddestroy () { - Super. Destroy (); - } the}

Text files: content.txt content

Java Programming C+ + programming C # programming

Browser display:

Example: servlet reads file contents and prints output on page

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.