2013-04-26 92 views
169

我想檢查文件夾中是否存在文件,但我不想創建一個新文件。Android;檢查文件是否存在,但不創建新文件

File file = new File(filePath); 
if(file.exists()) 
    return true; 

此代碼檢查沒有創建新文件嗎?

+2

這似乎是正確的。 – 2013-04-26 13:41:21

+0

可能重複的[測試如果文件存在](http://stackoverflow.com/questions/2786655/test-if-file-exists) – piokuc 2013-04-26 13:42:20

+1

@Kunok我在查看你的編輯評論:*刪除的話,如**坦克**,因爲他們是...... *:P – 2016-01-01 10:28:13

回答

316

你的代碼塊不會創建一個新的,它只會檢查它是否已經存在,沒有其他。

File file = new File(filePath); 
if(file.exists())  
//Do something 
else 
// Do something else. 
+3

不知道爲什麼在我的情況下,這段代碼正在創建一個新文件。 – ofnowhere 2014-02-19 20:54:59

+0

如何檢查子文件夾? – 2014-04-26 12:55:44

+4

這就是這樣,因爲沒有靜態方法:File.exists(String file),所以你必須實例化一個新的File對象來訪問'Exists'方法。 – Giova 2014-10-13 03:12:04

20

當您使用此代碼,你是不是創建一個新的文件,它只是創建該文件的對象引用,並測試它是否存在與否。

File file = new File(filePath); 
if(file.exists()) 
    //do something 
6

當你說「在你的包文件夾中」,你的意思是你的本地應用程序文件?如果是這樣,你可以使用Context.fileList()方法得到它們的列表。只需遍歷並查找您的文件。假設您保存了原始文件Context.openFileOutput()

示例代碼(在一個Activity):

public void onCreate(...) { 
    super.onCreate(...); 
    String[] files = fileList(); 
    for (String file : files) { 
     if (file.equals(myFileName)) { 
      //file exits 
     } 
    } 
} 
2

在Path類的methods是句法,這意味着它們在路徑實例進行操作。但最終,你必須訪問file系統驗證特定路徑存在

File file = new File("FileName"); 
if(file.exists()){ 
System.out.println("file is already there"); 
}else{ 
System.out.println("Not find file "); 
} 
3

它的工作對我來說:

File file = new File(getApplicationContext().getFilesDir(),"whatever.txt"); 
    if(file.exists()){ 
     //Do something 
    } 
    else{ 
     //Nothing 
    } 
0
public boolean FileExists(String fname) { 
     File file = getBaseContext().getFileStreamPath(fname); 
     return file.exists(); 
}