Android files get repeated - java

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

Related

Problem with Array list in java (always take the last element into the array)

I have a problem with array list
public void loadFiles(String folder, List<MyFile> listFiles) {
MyFile myfile = new MyFile();
File directory = new File(folder);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isDirectory()) {
loadFiles(file.toString());
}
if (file.isFile()) {
//set name and size to myfile
myfile.setName(file.getName());
myfile.setSize(file.length());
listFiles.add(myfile);
}
}
}
On folder (Myfolder) have 3 file (TC1,TC2,TC3).
but in listFiles output (TC1,TC1,TC1)
what is going on explain me.
And How to fix this issue
thanks
You are adding the same object to the List each time you loop through the files. You need to create a new file to add, not just change the name of myFile each time:
if (file.isFile()) {
//set name and size to NEW MyFile
MyFile newFile = new MyFile();
newFile .setName(file.getName());
newFile .setSize(file.length());
listFiles.add(newFile );
}
Thanks #Raj
"create a new instance like MyFile myfile = new MyFile(); inside the for loop and then add it to the listFiles. Currently you are just adding the same object multiple times." – Raj 1 min ago
public void loadFiles(String folder, List<MyFile> listFiles) {
File directory = new File(folder);
//get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
**MyFile myfile = new MyFile();**
if (file.isDirectory()) {
loadFiles(file.toString());
}
if (file.isFile()) {
//set name and size to myfile
myfile.setName(file.getName());
myfile.setSize(file.length());
listFiles.add(myfile);
}
}
}
It work .
Thanks All.
In your example, you want to get three different file instances in your list, but you create only one - you execute a new MyFile() only once in your code.
So you get three references to the same object. And whenever you change properties of that instance via myfile.setName(file.getName()); and myfile.setSize(file.length());, you see the change in all places where you reference this instance, so you get the same results in all three places of your list.
Instead of
myfile.setName(file.getName());
myfile.setSize(file.length());
you should do something like
myfile = new MyFile(file.getName(), file.length());
inside your loop.

Verify whether the file path contains particular String or not using java

I have one file path which is populated using File interface:-
File folder = new File("C:\\Program Files\\SmartBear\\ReadyAPI-2.2.0\\bin")
File[] listOfFiles = folder.listFiles();
File fOut = listOfFiles[0];
System.out.println(fOut)
It prints all the files inside bin folder. lets say, actions, ext, listeners
Now, I need to verify using if else statement whether the files inside the bin folder contains the particular file I am searching for?
Can we do it using java?
Here is a general example based on String.contains():
String expectedString = "PartOfFilename";
File folder = new File("/path/to/directory");
File[] listOfFiles = folder.listFiles();
for (File file : listOfFiles) {
if (file.getName().contains(expectedString)) {
//matching file found
}
}

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

Move inside a particular directory without knowing its name

I want to move inside a directory in Java but I don't know its name? Does Java provide any functionality to do so?
File srcFile = "C:/Entertainment/XXXXXXX/break.avi"
I am certain that there is only one directory inside Entertainment but I don't know its name. How can I move inside XXXXXXX directory to access any file inside it?
Any help?
Try,
File file = new File("C:/Entertainment");
File[] files = file.listFiles();
File srcDir = new File("C:/Entertainment/");
File srcFile = null;
for (File dirMember : srcDir.listFiles()) {
if (!dirMember.isDirectory()) {
continue; // we don't need regular files
}
if (dirMember.getName().equals(".")) {
continue; // we don't need this directory
}
if (dirMember.getName().equals("..")) {
continue; // we don't need the parent directory
}
// This is the one you need.
srcFile = new File(new File(srcDir, dirMember.getName()), "break.avi");
}
You could also use a FileFilter, e.g one from Commons IO
File dir = new File("C:/Entertainment/");
File[] files = dir.listFiles( DirectoryFileFilter.INSTANCE ); // returns all subdirs
srcFile = new File(files[0], "break.avi");
File srcFile = new File("C:\\Entertainment");
srcFile = new File(srcFile, srcFile.list()[0]);
srcFile = newFile(srcFile, "break.avi");
System.out.println(srcFile.getPath());
File outer= new File("C:/test");
File inner = outer.listFiles()[0];//if you are sure there is one
File[] listOfFilesInInnerMost = inner.listFiles();
System.out.println("Files: " + Arrays.asList(listOfFilesInInnerMost));
will print
Files: [C:\test\something\text (2).txt, C:\test\something\text (3).txt, C:\test\something\text.txt]

Categories

Resources