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?
To check for specific files use File. Exists(path) , which will return a boolean indicating wheter the file at path exists.
In Python, you can check whether certain files or directories exist using the isfile() and isdir() methods, respectively. However, if you use isfile() to check if a certain directory exists, the method will return False. Likewise, if you use if isdir() to check whether a certain file exists, the method returns False.
In order to check if a file exists in Bash using shorter forms, specify the “-f” option in brackets and append the command that you want to run if it succeeds. [[ -f <file> ]] && echo "This file exists!" [ -f <file> ] && echo "This file exists!"
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.
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;
Try this..............
File f = new File("./file_name");
if(f.exists()){
System.out.println("success");
}
else{
System.out.println("fail");
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With