// Counter. Java: A bean for reading and writing files
======================================
// The TXT format counter for website read/write operations
Package net.com. util;
Import java. Io .*;
Public class counter extends object {
Private string currentrecord = NULL; // variable for saving text
Private bufferedreader file; // bufferedreader object, used to read file data
Private string path; // complete file path name
Public counter (){
}
// The readfile method is used to read the data in the file filepath and return the data.
Public String readfile (string filepath) throws filenotfoundexception
{
Path = filepath;
// Create a new bufferedreader object
File = new bufferedreader (New filereader (PATH ));
String returnstr = NULL;
Try
{
// Read a row of data and save it to the currentrecord variable
Currentrecord = file. Readline ();
}
Catch (ioexception E)
{// Handle errors
System. Out. println ("Data reading error .");
}
If (currentrecord = NULL)
// If the file is empty
Returnstr = "no record ";
Else
{// The file is not empty.
Returnstr = currentrecord;
}
// Return the data to read the file
Return returnstr;
}
// The readfile method is used to write the counter + 1 data to the filepath of the text file.
// To increase the count
Public void writefile (string filepath, string counter) throws filenotfoundexception
{
Path = filepath;
// Convert counter to int type and add one
Int writestr = integer. parseint (Counter) + 1;
Try {
// Create a printwriter object for writing data to a file
Printwriter PW = new printwriter (New fileoutputstream (filepath ));
// Print the integer writestr in text format
PW. println (writestr );
// Clear the printwriter object
PW. Close ();
} Catch (ioexception e ){
// Handle errors
System. Out. println ("file writing error" + E. getmessage ());
}
}
}
==========================================
// Counter. jsp file
<% @ Page contenttype = "text/html; charset = GBK" %>
<! -- Create and call bean (Counter) -->
<JSP: usebean id = "counter" Scope = "page" class = "net.com. util. Counter"/>
<%
// Call readfileenders of the counterobject to read the count in lyfcount.txt.
String url = request. getrealpath ("count.txt ");
String cont = counter. readfile (URL );
// Call the readfilecounter of the counterobject to add the counter to the lyfcount.txt file.
Counter. writefile (URL, cont); %>
You are the <font color = "red"> <% = cont %> </font> visitor
==============================================
// Note: Create a count.txt file under the same counterfile .. The initial number is 0.
==============================================