checking if file exists in a specific directory

不问归期 提交于 2020-01-01 07:35:21

问题


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.

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?


回答1:


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? 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.




回答2:


This is where you have the bug.

String temp = file + ".MOD";

And

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

The code 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; 



回答3:


Try this..............

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


来源:https://stackoverflow.com/questions/11220678/checking-if-file-exists-in-a-specific-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!