文章来源于:http://songjianyong.iteye.com/blog/930091
Java代码:
package test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileReader; import java.io.FileWriter; public class CounterBean { private String path;//文件全路径 private String write;//要向文件写入的内容 private String read;//从文件读取的内容 public CounterBean(){} public int readFile(){//从文件读取内容 try { FileReader freader = new FileReader(path); BufferedReader breader = new BufferedReader(freader); read = breader.readLine();System.out.println("1 read="+read); String line = breader.readLine();System.out.println("2 line="+line); while(line!=null){ read = read+"<br>"+line;System.out.println("3 read="+read); line = breader.readLine();System.out.println("4 line="+line); } breader.close(); freader.close(); return 0; } catch (Exception e) { return -1; } } public int writeOver(){//向文件写入内容(write),原来内容将会被冲掉 try { FileWriter fwriter = new FileWriter(path); BufferedWriter bwrite = new BufferedWriter(fwriter); bwrite.write(write, 0, write.length()); bwrite.flush(); bwrite.close(); return 0; } catch (Exception e) { return -1; } } public int writeAppend(){//向文件追加写入内容(write),本次没有用到该方法 try { FileWriter fwrite = new FileWriter(path); BufferedWriter bwrite = new BufferedWriter(fwrite); bwrite.newLine(); bwrite.write(write, 0, write.length()); bwrite.flush(); bwrite.close(); return 0; } catch (Exception e) { return -1; } } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getWrite() { return write; } public void setWrite(String write) { this.write = write; } public String getRead() { return read; } public void setRead(String read) { this.read = read; } }
jsp代码
html代码
<%@ page language="java" pageEncoding="gb2312"%> <jsp:useBean id = "counterBean" class="test.CounterBean"></jsp:useBean> <html> <head> <title>计数器</title> <%! String filePath; %> </head> <body> <center> <% filePath =request.getRealPath("/")+"WEB-INF\count.txt"; counterBean.setPath(filePath); counterBean.readFile(); int count = Integer.parseInt(counterBean.getRead())+1; counterBean.setWrite(String.valueOf(count)); counterBean.writeOver(); out.print("总共访问人数:"+count); %> </center> </body> </html>