Convert File[] to String[] in Java - 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

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);

Just call File.list() instead.

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());

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();
}

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;
}

Why can't you try this?
driver.findElement(By.id(id1)).sendKeys(listOfFiles[1].getName());

Related

Java code to get the list of file name from a folder

I have a scenario where around 5600 files are present.
I am able to retrieve the file names by using the below code:
String path = "D:\\Projects worked upon\\ANZ\\Anz new\\Files\\329703588_20160328124733595\\Output"; String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.toLowerCase().endsWith(".xml"))
{
System.out.println(files);
}
, but i need only the first part For Eg:if the file name in folder is "abc_Transformed.xml" , i require only abc .. How to get it ?
You can use the substring method to find first string.
if (files.toLowerCase().endsWith(".xml"))
{
String result = files.substring(0, files.indexOf("_"));
System.out.println(result);
}
your whole code
String path = "D:\\Projects worked upon\\ANZ\\Anz new\\Files\\329703588_20160328124733595\\Output"; String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
if (files.toLowerCase().endsWith(".xml"))
{
String result = files.substring(0, files.indexOf("_"));
System.out.println(result);
}
The information about the files is basically irrelevant. You are after some basic String manipulation functions.
You could try something using String.split() like:
String[] pieces = files.split("_");
String first = pieces[0]; // should be equal to "abc"
Or something using String.indexOf() and String.substr() like:
int indexOfUnderscore = files.indexOf("_");
String first = files.substr(0, indexOfUnderscore); // should be equal to "abc"
If you're new to Java, it's worth spending the time to review all the String functions.

Convert a file array to string array JAVA

I need some help.
I use this code to get the files in a folder as an array .
String fileDir = Directorty;
File dir = new File(fileDir);
FileFilter fileFilter = new WildcardFileFilter("*.html");
files = dir.listFiles(fileFilter);
But I want to write a file with only the files in that folder and not the path.
The result is:
[C:\Askeladden-17-12-2014\.html, C:\Askeladden-17-12-2014\barnetv.html, C:\Askeladden-17-12-2014\britiskebiler.html, C:\Askeladden-17-12-2014\danser.html, C:\Askeladden-17-12-2014\disipler.html, C:\Askeladden-17-12-2014\donald.html, C:\Askeladden-17-12-2014\ekvator.html, C:\Askeladden-17-12-2014\engelskspraak.html]
But I want to have it without the path
C:\Askeladden-17-12-2014\
I have been looking around the webs to find some answers, but no luck.
Using this:
strFiles = Arrays.toString(files);
Gives a string presented as an array with [] in each end, and I am not able to get
strFiles.replace("C:\\Askleladden" + date +"\\", "");
to work.
You have to iterate the files array and call getName() for each file:
String[] names = new String[files.length];
for (int i = 0; i < files.length; i++) {
names[i] = files[i].getName();
}
Java 1.8, if you want get as List, just remove cast and to array
String[] files = (String[])Arrays.asList(dir.listFiles(filefilter))
.stream().map(x->x.getName())
.collect(Collectors.toList())
.toArray();
Please find the solution below with proper comments.
import java.io.File;
import java.io.FileFilter;
public class fileNames {
public static void main(String args[]){
//Get the Directory of the FOLDER
String fileDir = "/MyData/StudyDocs/";
// Save it in a File object
File dir = new File(fileDir);
//FileFilter fileFilter = new WildcardFileFilter("*.html");
//Capture the list of Files in the Array
File[] files = dir.listFiles();
for(int i = 0; i < files.length; i++){
System.out.println(files[i].getName());
}
}
}
Use Files getName() method:
File file = new File("myFolder/myFile.png");
System.out.println(file.getName()); //Prints out myFile.png

Java File Name Printing

I am trying to print name of files from two folders, and this code compiles but not giving anything on running it.
The main target here is to find common name files in two folders, I have stored file names in two arrays and then i will applying sorting and will find common files.
package javaapplication13;
import java.io.File;
import java.util.*;
public class ListFiles1
{
public static void main(String[] args)
{
String path1 = "C:/";
String path2 = "D:/";
File folder1 = new File(path1);
File folder2 = new File(path2);
String[] f1=folder1.list();
File[] listOfFiles1 = folder1.listFiles();
File[] listOfFiles2 = folder2.listFiles();
ArrayList<String> fileNames1 = new ArrayList<>();
ArrayList<String> fileNames2 = new ArrayList<>();
for (int i = 0; i < listOfFiles1.length; i++)
{
if (listOfFiles1[i].isFile())
{
fileNames1.add(listOfFiles1[i].getName());//wow
System.out.println(listOfFiles1[i].getName());
}
}
for (int i = 0; i < listOfFiles2.length; i++)
{
if (listOfFiles2[i].isFile())
{
fileNames2.add(listOfFiles2[i].getName());//seriously wow
}
}
}
}
Loop through both the ArrayLists you have. Each ArrayList contains the file names as it is. You'll need a nested loop (a loop inside a loop). In the core of the nested loops, you want to do a compare between current position of each ArrayList. You can use .equals() method for this. The pseudo code is something like:
//create a new ArrayList called "commonNameList"
// loop through fileNames1 with position variable "i"
//loop through fileNames2 with position variable "j"
//tempFileName1 = fileNames1.get(i)
//tempFileName2 = fileNames2.get(j)
//if tempFileName1 equals tempFileName2
//commonNameList.add(tempFileName1)
Check these out:
http://mathbits.com/MathBits/Java/Looping/NestedFor.htm
Simple nested for loop example
How do I compare strings in Java?
The main target here is to find common name files in two folders, I have stored file names in two arrays and then i will applying sorting and will find common files.
I don't like the two array thing. Also, a duplicate file should probably have the same length as well as the same name. If you are really going for just names, you can remove the f.length() == temp.length() part of the condition.
private static void findDups(String dirName1, String dirName2){
File dir1 = new File(dirName1);
File dir2 = new File(dirName2);
Map<String,File> fileMap = new HashMap<String,File>();
File[] files = dir1.listFiles();
for(File f : files){
fileMap.put(f.getName(),f);
}
files = dir2.listFiles();
StringBuilder sb = new StringBuilder(100);
for(File f : files){
File temp = fileMap.get(f.getName());
if(temp != null && f.length() == temp.length()){
sb.append("Found duplicate files: ")
.append(temp.getAbsolutePath())
.append(" and ")
.append(f.getAbsolutePath());
System.out.println(sb);
sb.delete(0,sb.length());
}
}
}

Fix for type mismatch error " file to string "

In the below code im list the files from the folders and passing the filepath to the method loadCSV. But I am getting type mismatch error here. plz help
String Folderfilename= list[i];
can saying "cannot convert file to string"
File foldername = new File(filename);
System.out.println("actual"+foldername);
File[] list = foldername.listFiles();
for(int i=0; i<list.length; i++){
System.out.println("inside for" +list.length);
String substring = list[i].getName().substring(0, list[i].getName().indexOf("."));
System.out.println("substring" +substring);
if(list[i].isFile() && list[i].getName().contains(".csv")) {
////////getting mismatch error in the below line
String Folderfilename= list[i];
new SCLoad().loadCSV(con,Folderfilename, ImportTable);
System.out.println("CLASS NAME "+list[i]);
}
}
Here in the line
String Folderfilename= list[i];
but your list is a array of type File object.
So you cannot assign like that.Type mismatch is there.
May be you need getName().
String Folderfilename= list[i].getName();
Please add proper checks before using the above line.
I presume you are looking for files ending with csv. You should probably use a FileNameFilter. Here's a snippet
File dir = new File("/tmp/");
File[] csvFiles = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith("csv"); //get all csv files
}
});
//now load these csvFiles using whatever loaders
for (File csvFile : csvFiles) {
// I am guessing SCLoad requires a complete path.
new SCLoad().loadCSV(con,csvFile.getCanonicalPath(), ImportTable);
}
Do this
File file = list[i];
String Folderfilename= file.getName()
Two changes in your code:
list[i].getName();
and
if( list[i].isDirectory() ) continue; //to avoid exception and to keep looking for csv files.
String folderFileName = "";
File foldername = new File(filename);
File[] list = foldername.listFiles();
for(int i=0; i<list.length; i++){
if( list[i].isDirectory() )
continue;
folderFileName = list[i].getName();
if( folderFileName.toLowerCase().endsWith(".csv") ) {
System.out.println("csv file: " + folderFileName);
new SCLoad().loadCSV(con,folderFileName, ImportTable);
}
}

Getting the names of files in the folder [duplicate]

This question already has an answer here:
output files from the folder with no extension
(1 answer)
Closed 8 years ago.
Decided to put the question differently, suppose we have a file-test, there is a lot of different files, some of this type indeks.html, kiki.tht, lololo.bin and so on, to get the names of all files in a folder, you can use this code:
File folder = new File("C:\\test\\");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
System.out.println(listOfFiles[i].getName());
}
}
But how to display only the file name without the extension? Indeks.html looolo.tht not like (just remember files in the lot, there is no duplicate names), and the index and looolo)
String fileName = listOfFiles[i].getName();
int index = fileName.lastIndexOf('.');
if (index >= 0) {
fileName = fileName.substring(0, index);
}
System.out.println(fileName);
String fullName = file.getName();
String nameWithoutExtension = fullName();
int lastDot = fullName.lastIndexOf(".");
if (lastDot >= 0) {
nameWithoutExtension = nameWithoutExtension.substring(0, lastDot);
}
You can get the name of the file and Split the String with
String[] file = filename.Split("\\.");'
file[0] holds the basename, whereas file[1] holds the extension.
Have you tried:
listOfFiles.get(index).getName()
Cheers
Apache Commons IO has a class called FilenameUtils, which offers the method getBaseName(String). Just hand in your file's path for the argument.

Categories

Resources