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