萬盛學電腦網

 萬盛學電腦網 >> 腳本專題 >> javascript >> 一個圖形計數器的例子

一個圖形計數器的例子

import java.io.*;
import java.util.*;
import com.sun.image.codec.jpeg.*;
import javax.servlet.*;
import javax.servlet.http.*;

import java.awt.*;
import java.awt.image.*;
public class JPEGServlet extends HttpServlet {

private String strFile="c:count.txt";
private Font mFont=new Font("Courier", Font.BOLD,12);;

public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {

String s;
int intCount;
s=getCount();
intCount=new Integer(s).intValue();
intCount=intCount+1;
writeCount(intCount+"");

response.setContentType("image/jpeg");
ServletOutputStream out=response.getOutputStream();
BufferedImage image=new BufferedImage(110,16,BufferedImage.TYPE_INT_RGB);
Graphics g=image.getGraphics();
g.setColor(Color.black);
g.fillRect(0,0,110,16);
g.setColor(Color.white);
g.setFont(mFont);

char c;
for(int i=0;i<10;i++) {
c=s.charAt(i);
g.drawString(c+"",i*11+1,12);
g.drawLine((i+1)*11-1,0,(i+1)*11-1,16);
}

JPEGImageEncoder encoder=JPEGCodec.createJPEGEncoder(out);
encoder.encode(image);
out.close();
}

public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {

doGet(request,response);
}

public synchronized void writeCount(String content) {
try {
PrintWriter pw = new PrintWriter(new FileOutputStream(strFile));
pw.println(content);
pw.close();
} catch(IOException e) {
System.out.println("Write file error:"+e.getMessage());
}
}

public synchronized String getCount() {
String strCount;
int len;
int leftLen;

try {
BufferedReader inf = new BufferedReader(new FileReader(strFile));
strCount=inf.readLine();
inf.close();
} catch(Exception e) {
System.out.println("Get counter error:"+e.getMessage());
return reChar('0',10);
}
len=strCount.length();
if (len<=0) {
return reChar('0',10);
}

if (len>10) {
return reChar('9',10);
}

leftLen=10-len;
return reChar('0',leftLen)+strCount;
}

private String reChar(char c,int num){
int i;
if (num<=0) return "";
String s="";
for(i=0;i<num;i++) {
s=s+c;
}
return s;
}
}
 

copyright © 萬盛學電腦網 all rights reserved