【发布时间】:2013-08-29 13:06:39
【问题描述】:
我有一个录音应用程序,我正在尝试实现一个功能来检查具有特定名称的录制文件是否已经存在。如果用户键入一个已经存在的文件名,应该会显示一个警告对话框。
所有文件名都存储在设备上的 .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();
}
【问题讨论】: