- <%@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>实例9:使用jsp读取TXT格式文件</title>
- </head>
- <body>
- <%
- //String filePath = request.getSession().getServletContext().getRealPath("/")+"JSP_Ajax"+"\\";
- //System.out.println("filePath=="+filePath);
- String path ="C:\\"; // 这边文件目录需改成相对路径
- File file = new File(path,"jsp.txt");
- FileReader fr = new FileReader(file); //字符输入流
- BufferedReader br = new BufferedReader(fr); //使文件可按行读取并具有缓冲功能
- StringBuffer strB = new StringBuffer(); //strB用来存储jsp.txt文件里的内容
- String str = br.readLine();
- while(str!=null){
- strB.append(str).append("<br>"); //将读取的内容放入strB
- str = br.readLine();
- }
- br.close(); //关闭输入流
- %>
- <center>
- <%=strB %>
- </center>
- </body>
- </html>
在这里File对象必须用绝对路径,”C:\\“ .此外,目录分隔符不能用”\“,必须用"\\'.
技巧:文本文件行的终止符为('\n')或('\r'),但是浏览器却不承认这些行的终止符。因此,为了让读取的文本内容在浏览器里显示换行,就必须在读取每一行的时候再后面加上HTML标签<br>