跟老紫竹学Java-计数器-文件版

来源:互联网 发布:淘宝详情图长度 编辑:程序博客网 时间:2024/04/30 00:40

原文地址:http://www.java2000.net/viewthread.jsp?tid=7256

 我们先看一个使用文件的代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%
  // 此文件的版权归
  // Java世纪网(http://www.java2000.net)和 CSDN(www.csdn.net)所有
  // 作者:老紫竹
  // 转载必须保留此版权声明
%>
<%@page import="java.io.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%!// 一个同步用的锁
  private static final Object lock = new Object();
  // 注意默认的文件目录在tomcat/bin目录下面
  private static final File file = new File("counter.dat");%>
Hello Word!
<%
  Integer count = 0;
  synchronized (lock) {
    // 我们从文件读取数据
    // 如果文件不存在,则需要初始化
    if (!file.exists()) {
      // 创建一个新的文件
      file.createNewFile();
      count = 0;
    } else {
      // 准备读取文件
      FileReader reader = new FileReader(file);
      // 从文件里读取int数据
      count = reader.read();
      // 关闭文件
      reader.close();
    }
    count++;
    // 准备写入文件
    FileWriter writer = new FileWriter(file);
    // 写入
    writer.write(count);
    // 关闭文件
    writer.close();
  }
%>
当前一共访问次数为:<%=count%>
</body>
</html>

 

再次强调,默认的文件目录在tomcat/bin目录下面。我们修改代码,将文件放到我们的项目的WEB-INF/classes目录下面
修改后的代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%
  // 此文件的版权归
  // Java世纪网(http://www.java2000.net)和 CSDN(www.csdn.net)所有
  // 作者:老紫竹
  // 转载必须保留此版权声明
%>
<%@page import="java.io.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%!// 一个同步用的锁
  private static final Object lock = new Object();
  // 注意默认的文件目录在tomcat/bin目录下面
  private static File file = null;%>
Hello Word!
<%
  Integer count = 0;
  synchronized (lock) {
    // 初始化文件名
    if (file == null) {
      file = new File(application.getRealPath(".")
          + "/WEB-INF/classes/counter.dat");
    }
    // 我们从文件读取数据
    // 如果文件不存在,则需要初始化
    if (!file.exists()) {
      // 创建一个新的文件
      file.createNewFile();
      count = 0;
    } else {
      // 准备读取文件
      FileReader reader = new FileReader(file);
      // 从文件里读取int数据
      count = reader.read();
      // 关闭文件
      reader.close();
    }
    count++;
    // 准备写入文件
    FileWriter writer = new FileWriter(file);
    // 写入
    writer.write(count);
    // 关闭文件
    writer.close();
  }
%>
当前一共访问次数为:<%=count%>
</body>
</html>

生成的文件如下:

后面我们将使用MySQL数据库进行存储

 







<script type="text/javascript"><!--google_ad_client = "pub-2908059660288034";/* 728x90,首页中间 创建于 08-8-14 */google_ad_slot = "5903610560";google_ad_width = 728;google_ad_height = 90;//--></script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击