導航:首頁 > 編程語言 > fileexistsjava

fileexistsjava

發布時間:2024-10-11 18:25:29

1. java判斷文件夾是否存在,不存在就創建

用File類中的exists()方法判斷是否存在;

用File類中的mkdirs創建文件目錄;

java代碼如下:

publicFilegetFile(Filefile){

//判斷文件夾是否存在
if(!file.exists()){

//不存在,則創建文件夾
file.mkdirs();
}

returnfile;
}

注意:

1. 首先明確一點的是:test.txt文件可以和test文件夾同時存在同一目錄下;test文件不能和test文件夾同時存在同一目錄下。

原因是:

(1)win的文件和文件夾都是以節點形式存放,這就意味著相同的文件和文件名不能處在同一目錄下,會命名沖突。

2. 基於以上原因,如果我想在d:創建一個test文件夾,但是d:下面有一個test文件,那麼由於命名沖突,是不可能創建成功的。

所以,在創建之前,要通過file.exists()判斷是否存在test命名的文件或者文件夾,如果返回true,是不能創建的;

(2)文件後綴名也算是文件名的一部分,即test.txt文件和test文件不是相同文件名的文件。

所以,在創建之前,要通過file.exists()判斷是否存在test命名的文件或者文件夾,如果返回true,是不能創建的;

然後再通過file.isDirectory()來判斷這是不是一個文件夾。

import java.io.File;

import java.io.IOException;


public class Main {


public static void main(String[] args) {


File file = new File("d:\test_file.txt");

Main.judeFileExists(file);


File dir = new File("d:\test_dir");

Main.judeDirExists(dir);

}


// 判斷文件是否存在

public static void judeFileExists(File file) {


if (file.exists()) {

System.out.println("file exists");

} else {

System.out.println("file not exists, create it ...");

try {

file.createNewFile();

} catch (IOException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


}


// 判斷文件夾是否存在

public static void judeDirExists(File file) {


if (file.exists()) {

if (file.isDirectory()) {

System.out.println("dir exists");

} else {

System.out.println("the same name file exists, can not create dir");

}

} else {

System.out.println("dir not exists, create it ...");

file.mkdir();

}


}


}

2. Java中怎樣根據文件的路徑去判斷該文件夾中是否存在該文件

1.File testFile = new File(testFilePath);
if(!testFile .exists()){
testFile.mkdirs();
System.out.println("測試文件夾不存在");
}

2.File testFile = new File(testFilePath);
if(!testFile .exists()){
testFile.createNewFile();
System.out.println("測試文件不存在");
}
java中File類自帶一個檢測方法exists可以判斷文件或文件夾是否存在,一般與mkdirs方法(該方法相較於mkdir可以創建包括父級路徑,推薦使用該方法)或者createNewFile方法合作使用。
1,如果路徑不存在,就創建該路徑

2,如果文件不存在,就新建該文件

3. java 中File類的exists()方法

就是如果存在的話返回「true」,否則就是返回「false」。舉例:
//判斷文件是否存在
public static String fileExists(String plainFilePath){
File file=new File(plainFilePath);
if(!file.exists()) {
return "false";
} else{

return "true";
}
}

閱讀全文

與fileexistsjava相關的資料

熱點內容
php按鈕點擊事件 瀏覽:934
河南伺服器機房售後服務雲主機 瀏覽:184
android仿聯系人 瀏覽:368
什麼app軟體可以學音標 瀏覽:669
郭天祥十天學會單片機優酷 瀏覽:330
什麼app兒童免費 瀏覽:582
遺傳演算法的理解 瀏覽:800
php刪除sql 瀏覽:841
紅進藍出指標源碼 瀏覽:700
python數據轉換列表類型 瀏覽:717
解壓後的文件怎麼解開 瀏覽:175
四川補貼認證下載什麼app 瀏覽:858
android設計風格 瀏覽:426
視頻不支持我的加密 瀏覽:342
布包pdf 瀏覽:267
程序員錄制課程表 瀏覽:626
eclipsephp斷點調試 瀏覽:895
虛擬成交量指標源碼 瀏覽:838
什麼APP有背單詞小組 瀏覽:43
蘋果2g視頻怎麼加密 瀏覽:204