简体   繁体   English

检查文件是否存在于特定目录中

[英]checking if file exists in a specific directory

I am trying to check for a specific file in a given directory. 我正在尝试检查给定目录中的特定文件。 I don't want the code but I want to fix the one I have. 我不想要代码,但我想修复我的代码。 The only difference in this question, is that I look for files with an extension .MOD . 这个问题的唯一区别是,我查找扩展名为.MOD文件。

I have the code ready:- 我准备好了代码: -

public static int checkExists(String directory, String file) {
    File dir = new File(directory);
    File[] dir_contents = dir.listFiles();
    String temp = file + ".MOD";
    boolean check = new File(temp).exists();
    System.out.println("Check"+check);  // -->always says false

    for(int i = 0; i<dir_contents.length;i++) {
        if(dir_contents[i].getName() == (file + ".MOD"))
            return Constants.FILE_EXISTS;
    }

    return Constants.FILE_DOES_NOT_EXIST;
}

But for some reasons, it does not work. 但由于某些原因,它不起作用。 I don't understand why, can anybody find any bug here? 我不明白为什么,有人能在这里发现任何错误吗?

Do you expect temp.MOD file to be in the current directory (the directory from which you run your application), or you want it to be in the "directory" folder? 您是否希望temp.MOD文件位于当前目录(运行应用程序的目录)中,或者您希望它位于“目录”文件夹中? In the latter case, try creating the file this way: 在后一种情况下,尝试以这种方式创建文件:

boolean check = new File(directory, temp).exists();

Also check for the file permissions, because it will fail on permission errors as well. 还要检查文件权限,因为它也会因权限错误而失败。 Case sensitivily might also be the cause of the issue as Spaeth mentioned. 案例敏感也可能是Spaeth提到的问题的原因。

This is where you have the bug. 这是你有bug的地方。

String temp = file + ".MOD";

And

if(dir_contents[i].getName() == (file + ".MOD"))

The code boolean check = new File(temp).exists(); 代码boolean check = new File(temp).exists(); will check for the file in the current directory not in the required directory. 将检查当前目录中不在所需目录中的文件。

    String dirName="/home/demo";
    File dir = new File(dirName);
    File[] dir_contents = dir.listFiles();
    String temp = dirName+"/"+"README" + ".MOD";
    boolean check = new File(temp).exists();
    System.out.println("Check" + check); // -->always says false

    for (int i = 0; i < dir_contents.length; i++) {
        if (dir_contents[i].getName().equals("README" + ".MOD"))
            return Constants.FILE_EXISTS;
            }

    return Constants.FILE_DOES_NOT_EXIST; 

Try this.............. 试试这个..............

File f = new File("./file_name");
if(f.exists()){
    System.out.println("success");
}
else{
    System.out.println("fail");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM