File operations are an important part of website programming. asp has discussed a lot about file operations. Let's take a look at how jsp is implemented.
Export to the test directory of the web root directory. After compiling the javabean file, place the class file under the corresponding class directory (tomcat environment ).
Read. jsp
<Html>
<Head>
<Title> read an object </title>
</Head>
<Body bgcolor = "#000000" type = "codeph" text = "/codeph">
<% -- Call javabean -- %>
<Jsp: useBean id = "reader" class = "DelimitedDataFile" scope = "request">
<Jsp: setProperty name = "reader" property = "path" value = "/test/afile.txt"/>
</Jsp: useBean>
<H3> file content:
<P>
<% Int count = 0; %>
<% While (reader. nextRecord ()! =-1) {%>
<% Count ++; %>
<B> row <% out. print (count); %>: </B>
<% Out. print (reader. returnRecord (); %> <br>
<% }%>
</P>
</Body>
</Html>
// DelimitedDataFile. java bean file source code
// Import the java package
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 the 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 ");
}
}
// Obtain the file path
Public String getPath (){
Return path;
}
// Close the file
Public void fileClose () throws IOException
{
File. close ();
}
// Read the next record. If no record exists,-1 is returned.
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;
}
}