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 the files in the F: \ gals folder, 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 need to convert listOfFiles [] to a String array, plz tell me an easy way to do this. thanks

+6
source share
6 answers

You do not need to convert the entire array. Just call the File method getAbsolutePath() :

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

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

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

Just call File.list() .

+7
source

I think you do not need to convert File [] to String []

Just use your file array as follows:

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

or, if you want to send the full path to the file:

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

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 the full path:

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

Another way: this is just a static helper method to convert an array of files into an array of String:

  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; } 
+2
source

Why can't you try this?

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

All Articles