2

I opted to use the isFile() method from this thread which requires absolute path to the file.

boolean doesFileExist = new File("C:/downloads/MyFile.txt").isFile();

I have gotten Selenium and Robot class to save the text file to a local directory but the file name is dynamic: MyTextFile_YYYYMMDDHHMMSS.txt. However, MyTextFile_ always remains the same. I want to check just with a partial file name match.

What is an elegant way to do this?

k_rollo
  • 5,304
  • 16
  • 63
  • 95
  • https://stackoverflow.com/questions/43272246/java-how-to-get-file-without-full-name?rq=1 – Thilo Aug 25 '17 at 12:20
  • Here you can find the solution to your problem https://stackoverflow.com/questions/8752034/how-to-check-a-file-if-exists-with-wildcard-in-java – solamente Aug 25 '17 at 12:21

1 Answers1

5

This code should help you.

First list out all the files in the folder

Start a loop and then get the fileName for each file and start comparing the name to do your job.

String folderName = "."; // Give your folderName
File[] listFiles = new File(folderName).listFiles();

for (int i = 0; i < listFiles.length; i++) {

    if (listFiles[i].isFile()) {
        String fileName = listFiles[i].getName();
        if (fileName.startsWith("MyTextFile_")
                && fileName.endsWith(".txt")) {
            System.out.println("found file" + " " + fileName);
        }
    }
}
nagendra547
  • 5,672
  • 3
  • 29
  • 43