Use jsp to read TXT files and jsp to read txt files
- <% @ Page import = "java. io. BufferedReader" %>
- <% @ Page import = "java. io. FileReader" %>
- <% @ Page import = "java. io. File" %>
- <% @ Page language = "java" contentType = "text/html; charset = UTF-8" pageEncoding = "UTF-8" %>
- <%
- // String path = request. getContextPath ();
- // System. out. println ("path =" + path );
- // String basePath = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + path + "/";
- %>
- <! DOCTYPE html PUBLIC "-// W3C // dtd html 4.01 Transitional // EN" "http://www.w3.org/TR/html4/loose.dtd">
- <Html>
- <Head>
- <Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8">
- <Title> instance 9: use jsp to read TXT files </title>
- </Head>
- <Body>
- <%
- // String filePath = request. getSession (). getServletContext (). getRealPath ("/") + "JSP_Ajax" + "\\";
- // System. out. println ("filePath =" + filePath );
- String path = "C :\\"; // you must change the file directory to a relative path.
- File file = new File (path, "jsp.txt ");
- FileReader fr = new FileReader (file); // character input stream
- BufferedReader br = new BufferedReader (fr); // enables the file to be read by row and has the buffer function
- StringBuffer strB = new StringBuffer (); // use strbto store content in the jsp.txt File
- String str = br. readLine ();
- While (str! = Null ){
- StrB. append (str). append ("<br>"); // Add the read content to strB
- Str = br. readLine ();
- }
- Br. close (); // close the input stream
- %>
- <Center>
- <% = StrB %>
- </Center>
- </Body>
- </Html>
Here, the File object must use an absolute path, "C: \". In addition, the directory separator cannot use "\", and must use "\\'.
Tip: The Terminator of a text file line is ('\ n') or (' \ R'), but the browser does not recognize the terminator of these lines. Therefore, to display a line break in the browser, you must add an HTML Tag after each line. <br>