下文筆者講述檢測文件或文件夾是否存在的方法分享,如下所示:
實現思路: 使用file.exists()方法即可檢測file對象是否為一個有效的路徑或文件夾 exists語法: public boolean exists() 返回值說明 true:文件或文件夾已經存在 false:此路徑不表示文件也不表示文件夾 異常說明 拋出SecurityException:SecurityManager.checkRead(String)時 則說明拒絕對目錄的讀取訪問
public static void main(String[] args) throws Exception { //判斷文件是否存在如果存在就刪除,不存在就新建 String path = "D:\\test"; String filename = "testfile.txt"; File file = new File(path, filename); //判斷文件或文件夾是否存在 boolean flag = file.exists(); if(flag) { //文件存在就要刪除文件 file.delete(); } else { //文件不存在就要新建文件 file.createNewFile(); } }