標籤:java color os 檔案 資料 io
1、建立進行讀寫檔案的java類
//寫檔案
public static void WriteFile(String filename,long counter) throws IOException {
PrintWriter out=new PrintWriter(new FileWriter(filename));
out.println(counter);
out.close();
}
//讀檔案
public static long ReadFile(String filename) {
long couter=0;
File f=new File(filename);
if(!f.exists()){
try {
WriteFile(filename, 0);
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedReader in=new BufferedReader(new FileReader(f));
try {
couter=Long.parseLong(in.readLine());
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
couter=0;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return couter;
}
2.jsp頁面調用
<%
String realPath = request.getSession().getServletContext()
.getRealPath("/")
+ "counter.txt";
long counter = Common.ReadFile(realPath);
if(session.getAttribute("visitor")==null){
session.setAttribute("visitor","yes");
session.setMaxInactiveInterval(3600);
counter++;
Common.WriteFile(realPath, counter);
}
%>
該頁面已被訪問<font color=‘red‘><%=counter%></font>次