我們先看一個使用檔案的代碼
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
// 此檔案的著作權歸
// Java世紀網(http://www.java2000.net)和 CSDN(www.csdn.net)所有
// 作者:老紫竹
// 轉載必須保留此著作權聲明
%>
<%@page import="java.io.*"%>
<!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>Insert title here</title>
</head>
<body>
<%!// 一個同步用的鎖
private static final Object lock = new Object();
// 注意預設的檔案目錄在tomcat/bin目錄下面
private static final File file = new File("counter.dat");%>
Hello Word!
<%
Integer count = 0;
synchronized (lock) {
// 我們從檔案讀取資料
// 如果檔案不存在,則需要初始化
if (!file.exists()) {
// 建立一個新的檔案
file.createNewFile();
count = 0;
} else {
// 準備讀取檔案
FileReader reader = new FileReader(file);
// 從檔案裡讀取int資料
count = reader.read();
// 關閉檔案
reader.close();
}
count++;
// 準備寫入檔案
FileWriter writer = new FileWriter(file);
// 寫入
writer.write(count);
// 關閉檔案
writer.close();
}
%>
當前一共訪問次數為:<%=count%>
</body>
</html>