我有一個語音錄製應用程序,我試圖實現一個功能,檢查具有特定名稱的錄製文件是否已經存在。如果用戶鍵入已存在的文件名,則應顯示警告對話框。如何檢查文件名是否已經存在?
所有文件名都存儲在設備上的.txt文件中。
我當前的代碼:
try {
BufferedReader br = new BufferedReader(new FileReader(txtFilePath));
String line = null;
while ((line = br.readLine()) != null) {
if (line.equals(input.getText().toString())) {
nameAlreadyExists();
}
}
br.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
newFileName = input.getText();
from = new File(appDirectory, beforeRename);
to = new File(appDirectory, newFileName + ".mp3");
from.renameTo(to);
writeToFile(input);
toast.show();
此代碼只因爲它應該工作半途而廢。它確實成功檢查文件名是否已經存在。如果文件名不存在,它將正常工作。但是,如果文件名已經存在,那麼用戶將會得到「nameAlreadyExists()」警告對話框,但該文件仍然會被添加和覆蓋。如何讓我的代碼在「nameAlreadyExists()」處停止?
我解決了這個問題用下面的代碼:
File newFile = new File(appDirectory, input.getText().toString() + ".mp3");
if (newFile.exists())
{
nameAlreadyExists();
}
else
{
newFileName = input.getText();
from = new File (appDirectory, beforeRename);
to = new File (appDirectory, newFileName + ".mp3");
from.renameTo(to);
writeToFile(input);
toast.show();
}
非常感謝!有很多答案,但你的是最簡單和最有效的,它的作品像一個魅力:) – Guy
如何檢查子文件夾? –