首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> JSP 程式設計 >> 關於JSP

JSP 文件讀取操作:JavaBean 封裝實現逐行讀取

     編輯:關於JSP

通過 JavaBean 封裝文件讀取邏輯,JSP 頁面使用 <jsp:useBean> 調用,實現文本文件逐行讀取並顯示行號。

JavaBean: DelimitedDataFile

package pkg; // 假設包名
import java.io.*; import java.util.StringTokenizer;
public class DelimitedDataFile {
    private String currentRecord; private BufferedReader file;
    private String path; private StringTokenizer token;

    public DelimitedDataFile() { file = new BufferedReader(new InputStreamReader(System.in),1); }
    public DelimitedDataFile(String filePath) throws FileNotFoundException {
        path = filePath; file = new BufferedReader(new FileReader(path));
    }
    public void setPath(String filePath) { /* 同構造器 */ }
    public String getPath() { return path; }
    public void fileClose() throws IOException { file.close(); }

    // 讀取下一行,返回 token 數,無數據返回 -1
    public int nextRecord() {
        try { currentRecord = file.readLine(); }
        catch(IOException e) { return -1; }
        if(currentRecord==null) return -1;
        token = new StringTokenizer(currentRecord);
        return token.countTokens();
    }
    public String returnRecord() { return currentRecord; }
}

JSP 調用頁面

<html><body>
<jsp:useBean id="reader" class="pkg.DelimitedDataFile" scope="request">
  <jsp:setProperty name="reader" property="path" value="/test/afile.txt"/>
</jsp:useBean>
<h3>文件內容:</h3>
<% int count=0; while(reader.nextRecord()!=-1) { count++; %>
  <b>第<%=count%>行:</b> <%=reader.returnRecord()%><br>
<% } %>
</body></html>

部署說明

  • Bean 編譯後 .class 放入 WEB-INF/classes/pkg/
  • 文本文件 afile.txt 放在 Web 根目錄 /test/ 下
  • Tomcat 環境下測試通過
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved