Js
File operation is one of the important content of Web programming, ASP on file operation has been discussed a lot, let's see how JSP is implemented.
Here used two files, a JSP file a JavaBean file, through the JSP call JavaBean can easily read text files, Note Place a text file Afile.txt to the Web root test directory, and JavaBean the class file to the corresponding class directory (Tomcat Environment) after the file is compiled.
read.jsp
<title> read a file </title>
<body bgcolor= "#000000" >
<%--Call JavaBean--%>
<jsp:usebean id= "Reader" class= "Delimiteddatafile" scope= "Request" >
<jsp:setproperty name= "Reader" property= "path" value= "/test/afile.txt"/>
</jsp:useBean>
<p>
<% int count = 0; %>
<% while (Reader.nextrecord ()!=-1) {%>
<% count++; %>
<b> <% Out.print (count); %> Line:</b>
<% Out.print (Reader.returnrecord ()); %><br>
<%}%>
</p>
</body>
Delimiteddatafile.java Bean File Source code
Importing Java Packages
Import java.io.*;
Import Java.util.StringTokenizer;
public class Delimiteddatafile
{
Private String CurrentRecord = null;
private BufferedReader file;
Private String path;
Private StringTokenizer token;
Create a File object
Public Delimiteddatafile ()
{
File = new BufferedReader (new InputStreamReader (system.in), 1);
}
Public Delimiteddatafile (String FilePath) throws FileNotFoundException
{
Path = FilePath;
File = new BufferedReader (new FileReader (path));
}
Set file path
public void SetPath (String filePath)
{
Path = FilePath;
try {
File = new BufferedReader (new
FileReader (path));
catch (FileNotFoundException e) {
SYSTEM.OUT.PRINTLN ("File not Found");
}
}
Get file path
Public String GetPath () {
return path;
}
Close File
public void FileClose () throws IOException
{
File.close ();
}
Read the next line of records, and if not, return-1
public int NextRecord ()
{
int returnint =-1;
Try
{
CurrentRecord = File.readline ();
}
catch (IOException E)
{
System.out.println ("ReadLine problem, terminating.");
}
if (CurrentRecord = null)
ReturnInt =-1;
Else
{
token = new StringTokenizer (CurrentRecord);
ReturnInt = Token.counttokens ();
}
return returnint;
}
Returns the entire record as a string
Public String Returnrecord ()
{
return currentrecord;
}
}