使用jsp讀取TXT格式檔案,jsp讀取txt格式
- <%@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>