---
title: "java防刷新网站计数器(BigInteger)"
author: "clplain"
date: "2011-02-27T15:26:13Z"
tags: []
categories: ["编程语言"]
slug: "java-biginteger"
draft: false
lastmod: "2011-02-27T15:26:13Z"
id: 932491
url: "https://clplain.iteye.com/blog/932491"
---

1:计数器的类;

package com;

import java.io.\*;  
import java.util.\*;  
import java.math.\*;  
/\**  
 * 防刷新的网站计数器;  
 * 使用BigInteger来存贮;  
 * @author clplain;  
 *  
 \*/  
public class count {  
 BigInteger count=null;  
 public BigInteger load(File file) throws Exception{  
  if(file.exists()){  
  Scanner scn=new Scanner(new FileInputStream(file));  
  if(scn.hasNext()){  
   count=new BigInteger(scn.next());  
  }  
  scn.close();  
  }else{  
    count=new BigInteger("0");  
    save(file,count);  
  }  
  return count;  
 }  
   
 public void save(File file,BigInteger count)throws Exception{  
  PrintStream ps=null;  
  ps=new PrintStream(new FileOutputStream(file));  
  ps.println(count);  
  ps.close();  
 }  
}  
2:计数器页面;

&lt;[%@page](mailto:%@page) contentType="text/html;charset=gb2312"%&gt;  
&lt;[%@page](mailto:%@page) import ="java.math.\*"%&gt;  
&lt;[%@page](mailto:%@page) import="java.util.\*"%&gt;  
&lt;[%@page](mailto:%@page) import="java.io.\*" %&gt;  
&lt;[%@page](mailto:%@page) import="com.count"%&gt;  
&lt;html&gt;  
&lt;head&gt;  
&lt;title&gt;网站计数器&lt;/title&gt;  
&lt;style type="text/css"&gt;  
&lt;!--  
body {  
 background-color: #99FFFF;  
}  
\--&gt;  
&lt;/style&gt;&lt;/head&gt;  
&lt;%!BigInteger count=null; %&gt;  
&lt;%String path=this.getServletContext().getRealPath("/")+"count.txt"; %&gt;  
&lt;%  
count t=new count();  
File file=new File(path);  
if(session.isNew()){  
 synchronized(this){  
 count=t.load(file);  
 count=count.add(new BigInteger("1"));  
 t.save(file,count);  
 }  
}  
%&gt;  
&lt;body topmargin="50"&gt;  
&lt;table width="401" height="30" border="1" align="right"&gt;  
  &lt;tr&gt;  
    &lt;td width="391" height="24" align="center"&gt;&lt;strong&gt;您是第&lt;%=count==null?0:count%&gt;位访问本站的用户&lt;/strong&gt;&lt;/td&gt;  
  &lt;/tr&gt;  
&lt;/table&gt;  
&lt;/body&gt;  
&lt;/html&gt;