在JSP中判斷某文件是否存在,並創建文件夾和文件。
備忘。
在WinXP + Tomcat5.1 中,代碼如下:
<%
//得到web根路徑//絕對路徑
//getServletContext().getRealPath("/")得到web應用的根路徑
// D:/web/excel,“D:/web”是web應用的根路徑,“excel”是根目錄下的文件夾
String Save_Location=getServletContext().getRealPath("/")+"excel//";
try{
if (!(new java.io.File(Save_Location).isDirectory())) //如果文件夾不存在
{
new java.io.File(Save_Location).mkdir(); //不存在 excel 文件夾,則建立此文件夾
new java.io.File(Save_Location)+"gmcc//").mkdir(); //創建excel文件夾下名爲 gmcc 的文件夾
}
else //存在excel文件夾,則直接建立此文件夾
{
new java.io.File(Save_Location)+"gmcc//").mkdir(); //創建 excel 文件夾下名爲gmcc的文件夾
}
}catch(Exception e){
e.printStackTrace(); //創建文件夾失敗
//在鏈接中使用URLEncoder編碼,傳遞中文參數。
//接收頁面可以使用getParameter()取得該參數,頁面的charset=GB2312。
String ErrName=java.net.URLEncoder.encode("文件夾不存在。創建文件夾出錯!");
response.sendRedirect("errorpage.jsp?error="+ErrName); //跳轉到錯誤頁面
return;
}
//在 gmcc 文件夾下新建 myfile.txt 文件
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[]= "你好!".getBytes();
fout.write(b);
fout.flush(); //寫入文件
fout.close(); //關閉
}
catch (java.io.FileNotFoundException e) {
e.printStackTrace();
}
catch (java.io.IOException ex) {
ex.printStackTrace();
}
%>