簡體   English   中英

如何檢查文件是否存在?

[英]How to check if a file exists?

我正在嘗試一種在外部存儲器上寫入txt純文件的方法。

它的工作原理! ..但我想在文件的頁腳中插入創建日期,方法是file.exists()方法。

如果存在,則不插入日期;如果不存在,則插入日期。

我的代碼是這個。

File idea=new File(dir,titulo+".txt");
            FileWriter writer=new FileWriter(idea);
            if (!(idea.exists())){
                texto.append("\n\n\tCreada :"+new Fecha().toString());
            }

假設該目錄是我的路徑。

    File dir =new File(Environment.getExternalStorageDirectory(),"/CMI");

titulo是metod在何時被調用的參數..並包含文件名。

(這是我的Date類,它以字符串形式返回Date)

File idea=new File(dir,titulo+".txt");
if (!idea.exists()){
    FileWriter writer = new FileWriter(idea);
    texto.append("\n\n\tCreada :" + new Fecha().toString());
    return;
}

試試上面的代碼。 如果您說FileWriter writer = new FileWriter(idea); 如果不存在,它將創建一個新文件。 因此, exist()方法沒有任何區別,並且始終返回true。

你能鑄模代碼嗎

File idea = new File(dir, titulo + ".txt");

if (idea.exists()){
    //do nothing
}
else {
    FileWriter writer=new FileWriter(idea);
    texto.append("\n\n\tCreada :" + new Fecha().toString());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM