【java】刪除上傳到伺服器的臨時檔案
阿新 • • 發佈:2018-12-15
刪除上傳到伺服器的臨時檔案
前言
此篇博文主要說明此前在解析excel檔案中上傳的excel檔案進行一個處理。
說明
- 伺服器 resin伺服器
- 程式碼操作 進行的程式碼實現全在jsp檔案中
- 用到File類
引用 java.io.File
- 工具 eclipse
正文
目的
刪除上傳到resin伺服器的臨時檔案。
背景
通過查詢JDK1.8說明文件,get到java.io
的exists(),isFile(),delete()
如下資訊所示
exists(): 檢查檔案或者目錄是否存在這種抽象路徑名 結果: true當且僅當檔案或目錄用這種抽象的路徑存在; false否則 isFile():
測試檔案是否通過這種抽象路徑名錶示的是一種正常的檔案。檔案是正常的,如果它不是一個目錄,此外,滿足其他系統相關的標準。任何非目錄檔案的java應用程式建立的保證是一個普通的檔案。 結果 : true 當且僅當檔案的抽象路徑名錶示存在,是一種正常的檔案; false否則 file.delete(): 刪除檔案或目錄的路徑名錶示的抽象。如果這個路徑表示目錄,然後目錄必須為空刪除。 結果 : true當且僅當檔案或目錄刪除成功; false否則
程式碼
說明 1:這裡博主實現了兩種方法進行為自己需求測試(也就是程式碼實現方式,編寫程式碼方式不同罷了) 2:具體的路徑根據自己要刪除的檔案路徑對待奧(路徑自定義)
第一種實現方式
package ceshi;
import java.io.File;
public class ceshi2 {
public static boolean deleteServerFile(String filePath, String fileName){
boolean delete_flag = false;
File file = new File(filePath + fileName);
if (file.exists() && file.isFile() && file.delete()) {
System.out.println("\n符合條件");
delete_flag = true;
} else {
delete_flag = false;
System.out.println("\n不符合條件,無法刪除指定檔案");
}
return delete_flag;
}
// 主方法
public static void main(String[] args) {
// 呼叫方法
deleteServerFile("D:/CSDN工作檔案/測試/", "SumatraPDF路徑.png");
}
}
第二種實現方式
package ceshi;
import java.io.File;
public class ceshi {
public static void main(String[] args) {
boolean delete_flag = false;
String filePath = "D:/CSDN工作檔案/測試/";
String fileName = "埠號錯誤.png";
String fPN = filePath + fileName;
File file = new File(fPN);
if (file.exists() && file.isFile() && file.delete()) {
System.out.println("\n符合條件");
delete_flag = true;
} else {
delete_flag = false;
System.out.println("\n不符合條件,無法刪除指定檔案");
}
}
}
測試結果
以上就是此次測試將伺服器上傳的臨時檔案刪除掉的一個說明過程。將程式碼引用到博主的專案需求中就是如下所示 部分程式碼
// 執行刪除resin伺服器上傳的臨時檔案
// System.out.println("\nin_filedir = " + in_filedir);
// in_filedir2=dqz_str.StrReplace(WEB_ROOT03,"/","\\"); // 已知的檔案路徑
// in_filename=my_file.getFileName();// 已知的檔名
boolean delete_flag = false;
// 獲取檔案路徑和檔名
String fPN = in_filedir2 + in_filename;
File file = new File(fPN);
if(file.exists() && file.isFile() && file.delete()) {
delete_flag = true;
System.out.println("\n符合判斷條件,上傳到resin伺服器的臨時檔案刪除成功!!!");
}else{
delete_flag = false;
System.out.println("\n 不符合判斷條件,上傳到resin伺服器的臨時檔案刪除失敗!!!");
}