Java 如何检查文件名是否已经存在?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18511874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:41:01  来源:igfitidea点击:

How to check if file name already exists?

javaandroid

提问by Guy

I have a voice recording app and I'm trying to implement a feature that checks if the recorded file with a certain name already exists. If a user types in a file name that already exists, an alert dialog should be shown.

我有一个录音应用程序,我正在尝试实现一项功能,以检查具有特定名称的录制文件是否已存在。如果用户输入的文件名已经存在,则应显示警告对话框。

All file names are stored in a .txt file on the device.

所有文件名都存储在设备上的 .txt 文件中。

My current code:

我目前的代码:

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();

This code only works halfway as it should. It does successfully check if the file name already exists. If the file name doesn't yet exist, it will work fine. But if the file name already exists, then the user will get the "nameAlreadyExists()" alert dialog but the file will still be added and overwritten. How do I make my code stop at "nameAlreadyExists()"?

这段代码只能正常工作一半。它确实成功地检查了文件名是否已经存在。如果文件名尚不存在,它将正常工作。但是如果文件名已经存在,那么用户将收到“nameAlreadyExists()”警告对话框,但该文件仍将被添加和覆盖。如何让我的代码在“nameAlreadyExists()”处停止?

I solved the problem with the following code:

我用以下代码解决了这个问题:

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();
            }

采纳答案by Konstantin Yovkov

The Fileclass provides the exists()method, which returns trueif the file exists.

File类提供的存在()方法,后者返回true文件是否存在。

File f = new File(newFileName);
if(f.exists()) { /* show alert */ }

回答by TN888

You can easy write return;to get out from the function (if that is the function). Or use

您可以轻松编写return;从函数中退出(如果那是函数)。或使用

if(f.exists() /* f is a File object */ ) /* That is a bool, returns true if file exists */

statement, to check if file exists and then do correct things.

语句,检查文件是否存在,然后做正确的事情。

回答by Spring Breaker

Below is the code i used to do the task,

下面是我用来完成任务的代码,

File mediaStorageDir = new File(
                    Environment
                            .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    "My_Folder");

            if (!mediaStorageDir.exists()) {
                if (!mediaStorageDir.mkdirs()) {
                    Log.d("My_Folder", "failed to create directory");
                    return null;
                }
            }

回答by KocsisLaci

I think you are missing some flag to fork your code in case the file does exist:

我认为您缺少一些标志来分叉您的代码,以防文件确实存在:

    boolean  fileExists = false;
    try {

    BufferedReader br = new BufferedReader(new FileReader(txtFilePath));
    String line = null;

    while ((line = br.readLine()) != null) {
        if (line.equals(input.getText().toString())) {
            fileExists = true;
            nameAlreadyExists();
        }
    }
    br.close();
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException ex) {
    ex.printStackTrace();
}
if(!fileExists)
{
 newFileName = input.getText();

 from = new File(appDirectory, beforeRename);
 to = new File(appDirectory, newFileName + ".mp3");
 from.renameTo(to);
 writeToFile(input);
 toast.show();
}

and feel free to use the exists() function of File as above....

并随意使用 File 的 exists() 函数,如上所述....