public class counter extends object {
private string currentrecord = null;//保存文本的變量
private bufferedreader file; //bufferedreader對象,用于讀取文件數據
private string path;//文件完整路徑名
public counter() {
}
// readfile方法用來讀取文件filepath中的數據,并返回這個數據
public string readfile(string filepath) throws filenotfoundexception
{
path = filepath;
// 創建新的bufferedreader對象
file = new bufferedreader(new filereader(path));
string returnstr =null;
try
{
// 讀取一行數據并保存到currentrecord變量中
currentrecord = file.readline();
}
catch (ioexception e)
{//錯誤處理
system.out.println("讀取數據錯誤.");
}
if (currentrecord == null)
// 如果文件為空
returnstr = "沒有任何記錄";
else
{//文件不為空
returnstr =currentrecord;
}
// 返回讀取文件的數據
return returnstr;
}
// readfile方法用來將數據counter+1后寫入到文本文件filepath中
// 以實現計數增長的功能
public void writefile(string filepath,string counter) throws filenotfoundexception
{
path = filepath;
// 將counter轉換為int類型并加一
int writestr = integer.parseint(counter)+1;
try {
// 創建printwriter對象,用于寫入數據到文件中
printwriter pw = new printwriter(new fileoutputstream(filepath));
// 用文本格式打印整數writestr
pw.println(writestr);
// 清除printwriter對象
pw.close();
} catch(ioexception e) {
// 錯誤處理
system.out.println("寫入文件錯誤"+e.getmessage());
}
}
}
====================================
// counter.jsp文件
<%@ page contenttype="text/html;charset=gbk"%>
<!--創建并調用bean(counter)-->
<jsp:usebean id="counter" scope="page" class="net.com.util.counter"/>
<%
//調用counter對象的readfile方法來讀取文件lyfcount.txt中的計數
string url=request.getrealpath("count.txt");
string cont=counter.readfile(url);
//調用counter對象的readfile方法來將計數器加一后寫入到文件lyfcount.txt中
counter.writefile(url,cont);%>
您是第<font color="red"> <%=cont%> </font>位訪問者
======================================
//注意:在counter的同一目錄下建立一個count.txt文件。。初始數字為0
======================================
新聞熱點
疑難解答