总访问人数每隔一段时间就变小,重新统计,是什么原因?代码见内
package util;
import java.io.*;
import java.lang.*;
import javax.servlet.http.HttpSessionListener;
import javax.servlet.http.HttpSessionEvent;
public class SessionCounter implements HttpSessionListener
{
private static int counterNow = 0; // 活动会话个数,即 当前在线人数。
private static int counterAll = 0; // 总访问人数。
/* Session创建事件 */
public void sessionCreated(HttpSessionEvent se)
{
counterNow++;
try
{
counterAll = 0; // 1 访问总人数
String strCountAll = "";
File fileCounter = new File("counter.txt");
if ( !fileCounter.exists() )
{
fileCounter.createNewFile();
}
else
{
BufferedReader bufReader = new BufferedReader(new FileReader("counter.txt"));
strCountAll = bufReader.readLine ();
counterAll = Integer.parseInt ( strCountAll );
bufReader.close ();
}
counterAll++;
PrintWriter pw = new PrintWriter ( new BufferedWriter(new FileWriter("counter.txt")) );
strCountAll = Integer.toString ( counterAll );
pw.println ( strCountAll );
pw.close ();
}
catch ( IOException e )
{
System.out.println ( e.toString() );
}
}
/* Session失效事件 */
public void sessionDestroyed(HttpSessionEvent se)
{
if ( counterNow > 0 )
counterNow--;
}
public static int getCounterNow()
{
return counterNow;
}
public static int getCounterAll()
{
try
{
String strCountAll = "";
File fileCounter = new File("counter.txt");
if ( !fileCounter.exists() )
{
fileCounter.createNewFile();
}
else
{
BufferedReader bufReader = new BufferedReader(new FileReader("counter.txt"));
strCountAll = bufReader.readLine ();
counterAll = Integer.parseInt ( strCountAll );
bufReader.close ();
}
}
catch ( IOException e )
{
System.out.println ( e.toString() );
}
return counterAll;
}
}