0

Good Morning, i have used these method to check if a certain file exists in a group of directories:

public static boolean doesFileExist(String[] directories, String fileName) {
    String path = " ";
    for (String dir : directories) {
        path = path + File.separator + dir;

    }
    System.out.println(path);
    File file = new File(path, fileName);
    return file.exists();
}

i give the method an array of directories and a file name which is actually exists in one of them, here's the array of directories:

    static String[] direstories = { "B:\\eslam\\xml", "B:\\eslam\\xml\\paper" };

and the file ch23.pdf does exists in the first directory, i think that the method takes a whole string of a group of directories and split it according to a regex like /^[A-z]+$/: but it violates my expectation as the method returns false with these group of directories \B:\eslam\xml\B:\eslam\xml\paper

Rob
  • 26,989
  • 16
  • 82
  • 98
Eslam Hamdy
  • 7,126
  • 27
  • 105
  • 165
  • That's not even remotely how the API works. I suggest you read the JavaDoc. http://docs.oracle.com/javase/7/docs/api/java/io/File.html#exists() – Matt Ball Apr 19 '13 at 13:52

2 Answers2

0

Isn't the scope of your loop wrong?

You'll only be checking against the last element in your array of directories I think.

DaveH
  • 7,187
  • 5
  • 32
  • 53
  • That should be a comment, perhaps! – AllTooSir Apr 19 '13 at 13:56
  • Could be - but it also answers why the code isn't doing what the OP expects. The file exists in the first directory, which he'll never actually be checking. – DaveH Apr 19 '13 at 13:59
  • Isn't the method above checks for the concatenation of the two directories?? it doesn't even check for the last directory as you said and that's what i'm asking about – Eslam Hamdy Apr 19 '13 at 14:06
  • The file.exists method does not work in the way that you are hoping. It'll look in the path shown by the System.out.println in your code above ( which will almost certainly not exist in your file system ) for a file called ch23.pdf. – DaveH Apr 19 '13 at 14:15
0

The method works only for a single path, actually a file instance should only point to a single file path.

Try this:

public static boolean doesFileExist(String[] directories, String fileName) {
for (String dir : directories) {
    System.out.println(dir+ File.separator+fileName);
    File file = new File(dir, fileName);
    if(!file.exists()) return false;
}
return true;}
carrizo
  • 65
  • 6
  • i don't want a working method, i just want to test the method with the code i have written with no change in sequence – Eslam Hamdy Apr 19 '13 at 14:08
  • I see, so the only way I think it would work is this way: static String[] direstories = { "B:", "eslam", "xml" }; – carrizo Apr 19 '13 at 14:13