user2181750
user2181750

Reputation: 259

file.exists() method returns false even if file exists

I created a program to display all files and sub-directories present in a directory,the directory name being passed as an argument from command line in cmd.
The first if condition(if(f.isDirectory())) checking whether the given argument is directory or not works fine.
Then i use File.list() method that is dir_content = f.list() to store a list of all filenames in the directory in an array of String dir_content.
Then in for loop ,each time a new file object is created for each file name stored in the String array dir_content that is File f1 = new File(dir_content[i]) and then check for existence of the file is made using exists() method that is if(f1.exists()).
Now problem is that f1.exists returns false for many of files despite of their existence in the given directory.It displays a few files, moreover doesn't show sub-directories.
Below is the code of my program:-

import java.io.File;
class FileDemo1
{
 public static void main(String[] a)
 {
  File f = new File(a[0]);
  String[] dir_content;   

  if(f.isDirectory())
  {
    System.out.print(f.getName()+" is a directory containing ");
    dir_content = f.list();

    for(int i=0;i<dir_content.length;i++)
    { 
        File f1 = new File(dir_content[i]);
        if(f1.exists())
        {
         System.out.print("\n\t: "+f1.getName());
         System.out.print("    "+f1.isFile());
         System.out.print("    "+f1.isDirectory());
        }
    }   

  }
 } 
}

Someone please tell me the reason behind the problem and its solution.
Thanks in advance.

Upvotes: 1

Views: 2551

Answers (2)

user_CC
user_CC

Reputation: 4776

dir_content[i] will only have directory name so when you will construct the File object it will only have the name of the Directory not the whole path, So that is why you get a false.

So if you do something like this it should give you true:

  File f1 = new File(f.getPath() + dir_content[i]);   ///f being a directory

Upvotes: 0

Martin
Martin

Reputation: 7714

Your logic is correct, but File.list does not do what you think. It returs a list of the files names, not their complete path, so you need to do something like :

 File f1 = new File(f,dir_content[i]);

to properly create the file path (your want the file "file1.txt" inside the given directory).

Upvotes: 2

Related Questions