jsp中ReaderFile方法来读取txt文件 WriterFile方法写入记录



jsp中利用UseBen 中的ReaderFile方法来读取txt文件 WriterFile方法写入记录,调用control对象的方法操作文件实例源码,jsp javabean操作txt文件实例:

JSP_File.jsp源文件:

<%@ page language=”java” pageEncoding=”utf-8″%>
<%@ page import=”com.cn.jspandfile.*” %>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<title>My JSP ‘JSP_File.jsp’ starting page</title>
</head>
<body>
<jsp:useBean id=”control” class=”com.cn.jspandfile.Control” scope=”request”/>
<%
String filePath = application.getRealPath(“/”)+”WEB-INF/control.txt”;
//调用control对象的ReaderFile方法来读取control.txt的信息
String count =control.ReaderFile(filePath);
//调用control对象的WriterFile方法把独具的记录数+1后写入文件control.txt中
control.WriterFile(filePath,count);
%>
第<font color=”red”><%=count %></font>访问者
</body>
</html>

 

Control.java源码:


package com.cn.jspandfile;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;

public class Control {
//保存文本的变量
private String currentRecord =null;
//BufferedReader对象,用于读取文件数据
private BufferedReader file;
//完整的文件路径对象
private String path;
public Control(){
}
//ReaderFile用来读取数据
public String ReaderFile(String filePath) throws FileNotFoundException{
path = filePath;
File file =new File(filePath);
if(!file.exists()){
//如果文件不存在,就创建一个文件
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//创建BufferReader对象
BufferedReader bufferedReader = new BufferedReader(new FileReader(path));
String str =null;

//读取一行数据,并保存到currentRecord变量中
try {
currentRecord = bufferedReader.readLine();
} catch (IOException e) {
// 处理错误
System.out.println(“读取数据错误!”);
}
//如果currentRecord变量为空
if(currentRecord ==null){
//文件为空
str = “1″;
}else{
//文件不为空
str = currentRecord;
}
return str;
}
public void WriterFile(String filePath,String count) throws FileNotFoundException{
path = filePath;
//把count转化为int类型并加上1
int writerStr = Integer.parseInt(count)+1;
try {
//创建PrintWriter对象,用于把数据写入文件中
PrintWriter printWriter = new PrintWriter(new PrintWriter(filePath));
printWriter.println(writerStr);
//清楚PrintWriter对象
printWriter.close();
} catch (IOException e) {
//处理错误
System.out.println(“文件写入错误”+e.getMessage());
}
}
}