Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 968
carol Avatar asked Jan 07 '16 10:01

carol


People also ask

How do you convert a file into string in Java?

Java read file to String using BufferedReader BufferedReader reader = new BufferedReader(new FileReader(fileName)); StringBuilder stringBuilder = new StringBuilder(); String line = null; String ls = System. getProperty("line. separator"); while ((line = reader. readLine()) !=

Can we convert string [] to string?

So how to convert String array to String in java. We can use Arrays. toString method that invoke the toString() method on individual elements and use StringBuilder to create String. We can also create our own method to convert String array to String if we have some specific format requirements.

What is new String [] in Java?

By new keyword : Java String is created by using a keyword “new”. For example: String s=new String(“Welcome”); It creates two objects (in String pool and in heap) and one reference variable where the variable 's' will refer to the object in the heap.

What does file toString do?

file. toString(); It will convert the specified pathname into the string.


2 Answers

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);
like image 192
Fred Porciúncula Avatar answered Sep 22 '22 16:09

Fred Porciúncula


Just call File.list() instead.

like image 30
user207421 Avatar answered Sep 20 '22 16:09

user207421