carol
carol

Reputation: 319

Convert File[] to String[] in Java

i have this code

File folder = new File("F:\\gals");
File[] listOfFiles = folder.listFiles();  

this code returns an array of locations of all files in folder F:\gals , and i tried to use this location in selenium code

driver.findElement(By.id(id1)).sendKeys(listOfFiles[1]);

and i see errors

The method sendKeys(CharSequence...) in the type WebElement is not applicable for the arguments (File)

so i think i have to convert listOfFiles[] to String array, plz tell me simple way to do this. Thanks

Upvotes: 7

Views: 4416

Answers (6)

Fred Porciúncula
Fred Porciúncula

Reputation: 8902

You don't need to convert the whole array. Just call File's getAbsolutePath() method:

driver.findElement(By.id(id1)).sendKeys(listOfFiles[1].getAbsolutePath());

But if you do want to convert the whole array, here is the Java 8 way to do this (simplified by @RemigiusStalder):

String listOfPaths[] = Arrays.stream(listOfFiles).map(File::getAbsolutePath)
        .toArray(String[]::new);

Upvotes: 12

user207421
user207421

Reputation: 310957

Just call File.list() instead.

Upvotes: 7

RichardK
RichardK

Reputation: 3471

Another way: this is just a static helper method to convert File array to String array:

 private static String[] convertFromFilesArray(File[] files){
        String[] result = new String[files.length];
        for (int i = 0; i<files.length; i++){
            result[i] = files[i].getAbsolutePath();
        }

        return result;
    }

Upvotes: 2

ThisaruG
ThisaruG

Reputation: 3412

If you want just the names:

String [] fileNames new String[listOfFiles.length];
  for (int i = 0; i < listOfFiles.length; i++) {
    fileNames[i] = listOfFiles[i].getName();
}

If you need full path:

String [] fileNames new String[listOfFiles.length];
  for (int i = 0; i < listOfFiles.length; i++) {
    fileNames[i] = listOfFiles[i].getPath();
}

Upvotes: 2

Ravindra Devadiga
Ravindra Devadiga

Reputation: 692

Why can't you try this?

driver.findElement(By.id(id1)).sendKeys(listOfFiles[1].getName());

Upvotes: 1

Ken Bekov
Ken Bekov

Reputation: 14015

I think, you don't need to convert File[] to String[]

Just use your file array this way:

driver.findElement(By.id(id1)).sendKeys(listOfFiles[1].getName());

or, if you would like to send full file path:

driver.findElement(By.id(id1)).sendKeys(listOfFiles[1].getPath());

Upvotes: 3

Related Questions