Example of reading and writing files in JSP

Source: Internet
Author: User
Example of reading a file
**************************************** ***********
<% @ Page contenttype = "text/html; charset = gb2312" %>
<%
// Variable Declaration/
Java. Lang. String strfilename; // file name
Java. Io. File objfile; // file object
Java. Io. filereader objfilereader; // read object
Char [] chrbuffer = new char [10]; // Buffer
Int intlength; // number of characters actually read (a Chinese character is a character)

// Set the file name to be read
Strfilename = "D: // test.txt ";

// Create a file object
Objfile = new java. Io. File (strfilename );

// Determine whether a file exists
If (objfile. exists () {// The object exists.
// Create a read object
Objfilereader = new java. Io. filereader (objfile );

// Read the file content
While (intlength = objfilereader. Read (chrbuffer ))! =-1 ){
// Output
Out. Write (chrbuffer, 0, intlength );
}

// Close the read object
Objfilereader. Close ();
}
Else {// the file does not exist
Out. println ("the following file does not exist:" + strfilename );
}
%>
**************************************** **********
Example of file writing
**************************************** **********
Use the printwriter object to write the text file.

See the following example:

<% @ Page import = "Java. Io. *" %>
<%
String STR = "Print me ";
// Always give the path from root. This way it almost always works.
String nameoftextfile = "/usr/Anil/imp.txt ";
Try {
Printwriter PW = new printwriter (New fileoutputstream (nameoftextfile ));
PW. println (STR );
// Clean up
PW. Close ();
} Catch (ioexception e ){
Out. println (E. getmessage ());
}
%>

Now, open imp.txt to check whether the string "Print me" has been written.

There is another way to mark the file tag of the library with in16, refer to http://sourceforge.net/project? Group_id = 1282.
The syntax of the example is as follows:
<Ext: file action = "Write | append | create | copy | move | Delete | rename | read" from = "<% = myfilename %>">

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.