Convert a file array to string array JAVA - 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

Related

Android files get repeated

I'm trying to list all the files in a directory.
Here is my code:
public List<String> MyFiles = new ArrayList<>();
dir = "/storage/sdcard0";
File f = new File(dir);
File[] files = f.listFiles();
for(File name: files) {
MyFiles.add(name.getName());
}
Collections.sort(MyFiles);
The problem is that nearly all the files is repeated.
For Instance I find .nomedia twice and sometimes thrice even thought there is only one file.
Edit:
I changed the code to sort the files correctly thanks to Vishwesh Jainkuniya, but still the same problem the files are repeated.
Problem-: sort function is not applicable for File[]
Solution:- create a string array and sort it.
Try this-:
First of all get the path of root dir
String path = Environment.getExternalStorageDirectory().toString();
Now append your dir name in path
path += "";
Now get the files in a array
File f = new File(path);
File file[] = f.listFiles();
String[] fileName = new String[file.length];
for (int i=0; i < file.length; i++)
{
fileName[i] = file[i].getName();
Log.d("Files", "FileName:" + file[i].getName());
}
Now sort
Arrays.sort(fileName);

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

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

Is it possible to store files of a folder in dynamic array in Java [duplicate]

This question already has answers here:
Finding common Files from two arrays
(2 answers)
Closed 9 years ago.
I am trying to find same name files in two folders.
I used File and listed names of file in two array list.
then i added common name files in two folders to a new arraylist and going to apply diff to find if these files are different or not.
As i have only stored name of files in Array List, i can't apply operation on those files directly.
Someone told me that by the use of dynamic array one can save files in Java...
My code till now with help of some great friends :
import java.io.File;
import java.util.*;
public class ListFiles1
{
public static void main(String[] args)
{
String path1 = "C:\\Users\\hi\\Downloads\\IIT Typing\\IIT Typing";
String path2 = "C:\\Users\\hi\\Downloads\\IIT Typing\\IIT Typing";
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());
// System.out.println(f1[i] + " is a file");
}
}
for (int j = 0; j < listOfFiles2.length; j++)
{
if (listOfFiles2[j].isFile())
{
fileNames2.add(listOfFiles2[j].getName());
}
}
ArrayList<String> commonfiles = new ArrayList<>();
for (int i = 0; i < listOfFiles1.length; i++)
{
for (int j = 0; i < listOfFiles2.length; j++)
{
String tempfilename1;
String tempfilename2;
tempfilename1=fileNames1.get(i);
tempfilename2 = fileNames2.get(j);
if(tempfilename1.equals(tempfilename2))
{
commonfiles.add(tempfilename1);
System.out.println(commonfiles);
}
}
}
}
}
Rather then having an ArrayList of Strings of the file names, just have an ArrayList of Files
List<File> filesList1 = Arrays.asList(folder1.listFiles());
List<File> filesList2 = Arrays.asList(folder2.listFiles());
Then when comparing if they have the same name then do your check of if it is a file and has the same name, then you have the reference to the File object and not just the name so you can read the files and see if they are the same.
for (File f1 : filesList1)
{
if(f1.isFile())
{
for (File f2 : filesList2)
{
if(f2.isFile() && f1.getName().equals(f2.getName))
{
commonfiles.add(f1.getName());
System.out.println(f1.getName());
}
}
}
}
This could be done way more efficiently with sets though
I'm not sure what your question actually is here, but I suggested that you use:
Set<String> dir1Files = new HashSet<String>();
Set<String> dir2Files = new HashSet<String>();
// load the sets with the filenames by iterating the File.listFiles() value, and using File.isFile() and File.getName() - just like your existing code
dir1Files.retainAll(dir2Files);
// now dir1Files contains the filenames that are the same in both directories
And if you need to work with the file itself, just recreate the File object:
File dir1File = new File(folder1, filename);
import java.io.File;
public class FileNameMatcher
{
public static void main(String[] args)
{
File folder1 = new File("C:/Users/pappu/Downloads");
File folder2 = new File("C:/Users/pappu");
for(String fileFromFolderOne:folder1.list())
{
for(String fileFromFolderTwo:folder2.list())
{
if(fileFromFolderOne.equals(fileFromFolderTwo))
{
System.out.println("match found");
System.out.println("file name is ===>>>"+fileFromFolderOne);
}
}
}
}
}

Categories

Resources