jsp檔案操作之讀取篇

來源:互聯網
上載者:User
js


檔案操作是網站編程的重要內容之一,asp關於檔案操作討論的已經很多了,讓我們來看看jsp中是如何?的。
  這裡用到了兩個檔案,一個jsp檔案一個javabean檔案,通過jsp中調用javabean可以輕鬆讀取文字檔,注意請放置一個文字檔afile.txt到web根目錄的test目錄下,javabean檔案編譯後將class檔案放到對應的class目錄下(tomcat環境)。
Read.jsp

<html>
<head>
<title>讀取一個檔案</title>
</head>
<body bgcolor="#000000">
<%--調用javabean --%>
<jsp:useBean id="reader" class="DelimitedDataFile" scope="request">
<jsp:setProperty name="reader" property="path" value="/test/afile.txt" />
</jsp:useBean>

<h3>檔案內容:</h3>

<p>

<% int count = 0; %>
<% while (reader.nextRecord() != -1) { %>
<% count++; %>
<b>第<% out.print(count); %>行:</b>
<% out.print(reader.returnRecord()); %><br>    
<% } %>
</p>
</body>
</html>


//DelimitedDataFile.java bean檔案原始碼
//匯入java包
import java.io.*;
import java.util.StringTokenizer;

public class DelimitedDataFile
{

private String currentRecord = null;
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)
        {
            
            path = filePath;
try {
file = new BufferedReader(new
FileReader(path));
} catch (FileNotFoundException e) {
            System.out.println("file not found");
            }
    
        }
//得到檔案路徑
     public String getPath() {
        return path;
}
//關閉檔案
public void fileClose() throws IOException
{
    
     file.close();
}
//讀取下一行記錄,若沒有則返回-1
public int nextRecord()
{
    
    
     int returnInt = -1;
     try
     {
     currentRecord = file.readLine();
     }
    
     catch (IOException e)
     {
     System.out.println("readLine problem, terminating.");
     }
    
     if (currentRecord == null)
     returnInt = -1;
     else
     {
     token = new StringTokenizer(currentRecord);
     returnInt = token.countTokens();
     }
     return returnInt;
}

    //以字串的形式返回整個記錄
public String returnRecord()
{

return currentRecord;
}
}






相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.