Create folders and files in JSP

Source: Internet
Author: User

In JSP, determine whether a file exists and create folders and files.

Memo.

In WINXP + tomcat5.1,CodeAs follows:

<%

// Obtain the web root path // absolute path
// Getservletcontext (). getrealpath ("/") to obtain the root path of the Web Application
// D:/web/Excel. "D:/Web" is the root path of the Web application, and "Excel" is the folder under the root directory.
String save_location = getservletcontext (). getrealpath ("/") + "Excel //";

Try {
If (! (New java. Io. File (save_location). isdirectory () // If the folder does not exist
{
New java. Io. File (save_location). mkdir (); // This folder is created if the Excel Folder does not exist.
New java. Io. File (save_location) + "gmcc //"). mkdir (); // create a folder named gmcc in the Excel folder
}
Else // If an Excel folder exists, this folder is created directly.
{
New java. Io. File (save_location) + "gmcc //"). mkdir (); // create a folder named gmcc in the Excel folder
}
} Catch (exception e ){
E. printstacktrace (); // failed to create the folder

// Use urlencoder encoding in the link to pass Chinese parameters.
// You can use getparameter () to obtain this parameter on the receiving page. charset of the page is gb2312.
String errname = java.net. urlencoder. encode ("the folder does not exist. An error occurred while creating the folder! ");
Response. sendredirect ("errorpage. jsp? Error = "+ errname); // jump to the error page
Return;
}

// Create the myfile.txt file in the gmcc folder
Java. Io. File myfile = new java. Io. File (save_location + "gmcc // myfile.txt ");
Java. Io. fileoutputstream fout = NULL;
Try {
Fout = new java. Io. fileoutputstream (myfile );
Byte B [] = "Hello! ". Getbytes ();
Fout. Write (B );
Fout. Flush (); // write the file
Fout. Close (); // close
}
Catch (Java. Io. filenotfoundexception e ){
E. printstacktrace ();
}
Catch (Java. Io. ioexception ex ){
Ex. printstacktrace ();
}

%>

J. R. Q.

2005.11.17 at Spike

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.