做了个(文本)计数器

感觉操作数据库不是很快,于是作了个文本计数器,servlet的,其实很多代码网上都有.再win2000s+tomcat5.0下测试通过.代码如下:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class counter extends HttpServlet {
  private static final String CONTENT_TYPE = "text/html; charset=GBK";
  String countNums[] =null;
  String countNum[]=null;
  String counts[]=null;
  String temper=null;
   int  count=0;
   int counters=0;
    String path="e://counter.txt";//可以自己定义文件的路径,counter.txt里面设置初始值(int型!)
   int numLen =0;

//Initialize global variables
  public void init() throws ServletException {
  }
  //Process the HTTP Get request
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {
    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    counts=this.counting();
    for(int i=0;i<counts.length;i++)//一般说来访问量不会超过这个的最大值吧
    {
   out.print(counts[i]);
    }


  }
  //Clean up resources

  public void destroy() {
  }
  public  void doPost(HttpServletRequest request,HttpServletResponse response)
   throws ServletException,IOException{
  doGet(request,response);
  }

 

public  String[]  counting()  throws IOException{//逐个取出数字
    try {
      FileReader fr = new FileReader(path);
      BufferedReader br=new BufferedReader(fr);
      String Line=br.readLine();
     if (Line!=null)
      {
         temper=Line;
         numLen =Line.length();
         countNums=new String[numLen];
         countNum=new String[numLen];
       for(int l = 0; l <= numLen - 1; l++)
        {
            countNum[l] =Line.substring(l++, l);
            l--;
            countNums[l] = "<img src='../../counter/"+countNum[l] + ".jpg' width='20'

height='29'>";//将包含图片的counter文件夹放在webapps下,图片格式为jpg,文件名为0-9;

          }
        br.close();
        fr.close();
       this.addNum();
   }
 }

catch(Exception exception)
        {
            System.out.println("Init Error:" + exception);
        }
      return  countNums;
}
public  void addNum()
{
try {
 File txt= new File(path);
 PrintWriter out = new PrintWriter(new FileWriter(txt));
 count=Integer.parseInt(temper.toString());
 counters=count+1;//计数器增加一
 out.print(counters);//写入文件counter.txt
 out.close();
}
    catch (IOException e) {
System.out.print(e.toString());
        }
     }
   }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值