Examples of reading and writing files in JSP

Source: Internet
Author: User
Examples of JS read files
***************************************************
<%@ page contenttype= "text/html;charset=gb2312"%>
<%
Variable declaration \
Java.lang.String strFileName; Filename
Java.io.File objfile; File objects
Java.io.FileReader Objfilereader; Read File objects
char[] Chrbuffer = new CHAR[10]; Buffer
int intlength; The number of characters actually read (one character in Chinese)

Set the file name to read
strFileName = "D:\\test.txt";

Create a File object
objfile = new Java.io.File (strFileName);

To determine whether a file exists
if (objfile.exists ()) {//File exists
Create a read file object
Objfilereader = new Java.io.FileReader (objfile);

Read the contents of the file
while ((Intlength=objfilereader.read (Chrbuffer))!=-1) {
Output
Out.write (chrbuffer,0,intlength);
}

Close the Read file object
Objfilereader.close ();
}
else{//file does not exist
Out.println ("The following file does not exist:" +strfilename);
}
%>
**************************************************
Examples of writing files
**************************************************
The text file can be written using the PrintWriter object.

Please refer to the following example:

<%@ page import= "java.io.*"%>
<%
String str = "Print Me";
Always give the path from root. This is 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 see that the string "Print me" should already be written.

There is another way to use the IN16 tag Library's file tag to refer to http://sourceforge.net/project/?group_id=1282.
The syntax for the example is:
<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.