Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Westi on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Finding a file in derectory 1

Status
Not open for further replies.

developer155

Programmer
Jan 21, 2004
512
US
What is the easiest way in java to search a given directory for a file. I have a directory and folder path where I have to fina a file, with name like MyFile.GIF. How can I do it with Java

thanks
 
Hi,

Try this.. it will return you boolean value if the file exists in a directory..

public class DetermineFileDirExists {

private static void doTest() {

// Create a File object
File file1 = new File("README_InputFile.txt");
File file2 = new File("BlaBlaBla.txt");

boolean b = file1.exists();
System.out.println();
System.out.println("Does File/Dir " + file1 + " exist? (" + b + ")\n");

b = file2.exists();
System.out.println();
System.out.println("Does File/Dir " + file2 + " exist? (" + b + ")\n");


}
public static void main(String[] args) {
doTest();
}

}

Cheers,
Venu
 
Venu, but where do you specify the directory? I only see you specify 2 text files. I need to give a directory and a file to search for in that directory

Liek my directory is c:\docs\folder
File name is Picture.GIF

thanks
 
Code:
public boolean find(String dir, String file) {
  File d = new File(dir);
  File[] files = d.listFiles(); 
  for (int i = 0; i < files.length; i++) {
    if (files[i].toString().equals(file)) {
       return true;
    }
  }
  return false;
}
 
damn TGML is broken :

Code:
public boolean find(String dir, String file) {
  File d = new File(dir);
  File[] files = d.listFiles(); 
  for (int j = 0; j < files.length; j++) {
    if (files[j].toString().equals(file)) {
       return true;
    }
  }
  return false;
}

BTW, it oftens helps to read the manual !!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top