Java list files in a folder avoiding .DS_Store - java

When I try to list files in a folder with this:
String file;
File folder = new File("/Users/francesco/Desktop/VIDEOS");
File[] listOfFiles = folder.listFiles();
BufferedReader br = null;
for (int i = 0; i < listOfFiles.length; i++){
It reads also the .DS_Store file inside the folder, giving me a lot of errors. How can I avoid to read these .DS_Store files in Java?

You can pass a FileNameFilter to File.listFiles to filter out the one you don't want.
File[] files = folder.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return !name.equals(".DS_Store");
}
});
EDIT: Java 8 lambda version
File[] files = folder.listFiles((dir, name) -> !name.equals(".DS_Store"));

Related

How to access the folder name from the directory

I want to get the name of the folders from directory who only have .c and .h files.
below is my code but I am not getting that how exactly I can get the folder names who only have .c and .h files.
File directory = new File(directoryName);
//get all the files from a directory
if(directory.exists()){
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isDirectory()){
System.out.println(file.getName());
System.out.println(file.getAbsolutePath());
}
Above code will take the input path for directory and prints the name of all sub folders or sub directories if the main directory is exist.and also prints the path.Now I only want the name of all sub folders from directory which have .c and .h files.
Thanks If anyone help me.
Try to take a look at Apache's DirectoryScanner
Using that we can mention the file extension types to be considered/omitted
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"*.c", "*.h"});
https://ant.apache.org/manual/api/org/apache/tools/ant/DirectoryScanner.html
You can use a list and getParent() function like:
List<String> list;
File directory = new File(directoryName);
if(directory.exists()){
File[] fList = directory.listFiles();
for (File file : fList){
if (file.isDirectory()){
System.out.println(file.getName());
if(file.getName().contains(".c") || file.getName().contains(".h"))
list.add(file.getParent());
System.out.println(file.getAbsolutePath());
}
}
}
for(String item : list) {
System.out.println(item);
}
I've given a pure Java solution here, but if your directory structure is too deep or directories have thousands of files, this may not work out. In that case you may have to run an OS command and dump the output into Java. For instance if you use Unix (or Unix-based) system, you can use find to list directories and invoke the command from Java using ProcessBuilder.
Now the Java solution:
Create a custom FileNameFilter first. This will filter files based on extensions you pass.
public class ExtensionFilter implements FilenameFilter {
private String[] extensions;
public ExtensionFilter(String... extensions) {
this.extensions = extensions;
}
#Override
public boolean accept(File dir, String name) {
for (String extension : extensions) {
if ( name.toLowerCase().endsWith(extension.toLowerCase()) ) {
return true;
}
}
return false;
}
}
Create a FileFilter to help you filter for only directories (for recursion)
public class FolderFilter implements FileFilter {
#Override
public boolean accept(File path) {
return path.isDirectory();
}
}
Use recursion to build list of folder paths contains files with the given extension.
private static final FolderFilter folderFilter = new FolderFilter();
public List<String> recursiveSearch(File base, ExtensionFilter extFilter) {
List<String> paths = new ArrayList<>();
//Does current directory itself have files of given extension?
if (base.list(extFilter).length > 0) {
paths.add(base.getPath()); //Use base.getName() here instead, for just name
}
// Recurse through current directory's subfolders
for (File dir : base.listFiles(folderFilter)) {
paths.addAll(recurse(dir, extFilter));
}
return paths;
}
Finally, invoke it like so:
String basePath = "...";
File baseDir = new File(basePath);
ExtensionFilter extFilter = new ExtensionFilter(".c",".h");
List<String> folders = recurse(baseDir, extFilter);
This will now contain all paths (or names as mentioned above) of folders which have files with given extensions.

how get a specific file onItemClick from list view

i have a folder with two files: one pdf and one xml.
When i click on folder i want get path of xml file only.
With my code(that i post below) i get paths of both files.
Who can help me?
THANKS!
private ArrayList<String> GetFiles2(File f) {
ArrayList<String> MyFiles = new ArrayList<String>();
//File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for (int i=0; i<files.length; i++)
MyFiles.add(files[i].getPath());
}
System.out.println("MYFILE:"+MyFiles);
return MyFiles;
}
my result : MYFILE:
`[/storage/emulated/0/ordinazioni/2/23_Agosto_2017_09_44_51_AM.xml,` /storage/emulated/0/ordinazioni/2/23_Agosto_2017_09_44_51_AM.pdf]
You can use the overriden version of File#listFiles(FileFilter) to get specific files from a directory.
File[] files = f.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".xml");
}
});
Full implementation :
private ArrayList<String> getXmlFiles(File directory) {
ArrayList<String> names = new ArrayList<>();
directory.mkdirs();
File[] files = directory.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.getName().endsWith(".xml");
}
});
for(File f : files)
names.add(f.getPath());
System.out.println("MYFILE:" + names);
return files.length > 0 ? names : null;
}
Anyway I recommend you to return an empty list insteand of null to avoid NPE issues (Just return names)
You can change your for-loop like this for example:
for (int i=0; i<files.length; i++) {
if(files[i].getPath().endsWith(".xml")) {
MyFiles.add(files[i].getPath());
}
}
this will add to the MyFiles list only the paths of the xml files in the praticular folder
For getting a specific file location use this code,
File dir = Environment.getExternalStorageDirectory();
File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");
eg ;
"/AAlist/"+serialno.get(position).trim()+".jpg"

find specific file type from folder and its sub folder

I am writing a method to get specific file type such as pdf or txt from folders and subfolders but I am lacking to solve this problem. here is my code
// .............list file
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
System.out.println(file.getAbsolutePath());
} else if (file.isDirectory()) {
listf(file.getAbsolutePath());
}
}
My current method list all files but I need specific files
For a filtered list without needing recursion through sub directories you can just do:
directory.listFiles(new FilenameFilter() {
boolean accept(File dir, String name) {
return name.endsWith(".pdf");
}});
For efficiency you could create the FilenameFilter ahead of time rather than for each call.
In this case because you want to scan sub folders too there is no point filtering the files as you still need to check for sub folders. In fact you were very nearly there:
File directory = new File(directoryName);
// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {
if (file.getName().endsWith(".pdf")) {
System.out.println(file.getAbsolutePath());
}
} else if (file.isDirectory()) {
listf(file.getAbsolutePath());
}
}
if(file.getName().endsWith(".pdf")) {
//it is a .pdf file!
}
/***/
Try using the FilenameFilter interface in you function
http://docs.oracle.com/javase/6/docs/api/java/io/FilenameFilter.html
http://www.mkyong.com/java/how-to-find-files-with-certain-extension-only/ - for a code that has extention filter
Use File.listFiles(FileFilter).
Example:
File[] fList = directory.listFiles(new FileFilter() {
#Override
public boolean accept(File file) {
return file.getName().endSwith(".pdf");
}
});
You can use apache fileUtils class
String[] exte= {"xml","properties"};
Collection<File> files = FileUtils.listFiles(new File("d:\\workspace"), exte, true);
for(File file: files){
System.out.println(file.getAbsolutePath());
}
My advice is to use FileUtils or NIO.2.
NIO.2 allows Stream with Depth-First search, for example you can print all files with a specified extension in one line of code:
Path path = Path.get("/folder");
try{
Files.walk(path).filter(n -> n.toString().endsWith(".extension")).forEach(System.out::println)
}catch(IOException e){
//Manage exception
}

How to get all the filenames in android directory?

Im trying to list all the files in a particular folder of my android emulator and i keep getting null answer.
Heres my code:
File sdCardRoot = Environment.getExternalStorageDirectory();
File[] file= new File(sdCardRoot+"path");
for (File f : file.listFiles()) {
if (f.isFile())
String name = f.getName();
}
This doesnt seem to work dont know why.
I've split the function in two parts, first function gets all the files in the given path and the second function gets the filenames from the file array.
public File[] GetFiles(String DirectoryPath) {
File f = new File(DirectoryPath);
f.mkdirs();
File[] file = f.listFiles();
return file;
}
public ArrayList<String> getFileNames(File[] file){
ArrayList<String> arrayFiles = new ArrayList<String>();
if (file.length == 0)
return null;
else {
for (int i=0; i<file.length; i++)
arrayFiles.add(file[i].getName());
}
return arrayFiles;
}
change
File[] file= new File(sdCardRoot+"path");
with
File[] file= new File(sdCardRoot, "path");
and make sure the directory path exits
Just Check this:
List<File> files = getListFiles(new File("YOUR ROOT"));
private List<File> getListFiles(File parentDir) {
ArrayList<File> inFiles = new ArrayList<File>();
File[] files = parentDir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
inFiles.addAll(getListFiles(file));
} else {
if(file.getName().endsWith(".csv")) {
inFiles.add(file);
}
}
}
return inFiles;
Since sdCardRoot is instance of File, sdCardRoot+"path" will return the same thing as sdCardRoot.toString() + "path".
However, calling file.toString() returns file name, but not absolute path. You need to call sdCardRoot.getAbsolutePath() + "path".
Also, make sure that you have allowed the emulator to use a certain amount of memory for external storage.

Scan a file folder in android for file paths

So i have a folder at "mnt/sdcard/folder" and its filled with image files. I want to be able to scan the folder and for each of the files that is in the folder put each file path in an arraylist. Is there an easy way to do this?
You could use
List<String> paths = new ArrayList<String>();
File directory = new File("/mnt/sdcard/folder");
File[] files = directory.listFiles();
for (int i = 0; i < files.length; ++i) {
paths.add(files[i].getAbsolutePath());
}
See listFiles() variants in File (one empty, one FileFilter and one FilenameFilter).
Yes, you can use the java.io.File API with FileFilter.
File dir = new File(path);
FileFilter filter = new FileFilter() {
#Override
public boolean accept(File file) {
return file.getAbsolutePath().matches(".*\\.png");
}
};
File[] images = dir.listFiles(filter);
I was quite surprised when I saw this technique, as it's quite easy to use and makes for readable code.

Categories