CSDN博客

img flice

做了个(文本)计数器

发表于2004/2/20 11:16:00  680人阅读

感觉操作数据库不是很快,于是作了个文本计数器,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());
        }
     }
   }

0 0

相关博文

我的热门文章

img
取 消
img