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.
Related
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.
So I have csvs:
R-15_A.csv
R-16_A.csv
R-17_A.csv
R-15_B.csv
R-15_A_Processed.csv
R-15_B_Processed.csv
R-16_A_Processed.csv
R-17_A_Processed.csv
Been using commons.io's wildcardfilefilter but am confused at the filter.
So if I wanted to get a list of files that are A but not processed what would I use for the filter?
File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("filter?");
File[] files = dir.listFiles(fileFilter);
for(File f:files)
{
log.info("service2: "+f.getName());
}
log.info("service2: size "+files.length);
"*A.csv" should match 'A' but not 'Processed'
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"));
I'm making a media player. I want to get all videos present in the sd card.
If the video is directly available in top directory of sd card, it is simple. But what about a video file exists in nested directory structure like
directory->directory->directory->file.mp4.
How can I search for a file in a nested directory structure?
You can create a list which can store the location of all the video files present on sd card. Run a loop which will visit every folder and update this array if given file format (in your case video files or .mp4) and add it to array. You can store this list onto persistent storage so as you can read it the next time your application is launched.
Here is sample code which can help you list all files in sdcard
public ArrayList<File> getfile(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null && listFile.length > 0) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
fileList.add(listFile[i]);
getfile(listFile[i]);
} else {
if (listFile[i].getName().endsWith(".png")
|| listFile[i].getName().endsWith(".jpg")
|| listFile[i].getName().endsWith(".jpeg")
|| listFile[i].getName().endsWith(".gif")) {
fileList.add(listFile[i]);
}
}
}
}
return fileList;
}
With Apache FileUtils:
import org.apache.commons.io.FileUtils;
String path = ...;
String[] extensions = {"mp4", "mov", ...};
Collection<File> allMovies = FileUtils.listFiles(new File(path), extensions, true);
am posting this, maybe it would help some one in need.
as #Jaqen H'ghar said ... i just simplify the code to add the list of the extensions u want to show.
File filePath = new File(Environment.getExternalStorageDirectory().getAbsolutePath());
List<String> fileList = new ArrayList<>();
String[] extensions = {"apk","mp3","mp4","or what ever extension u want"};
Collection<File> allMovies = FileUtils.listFiles(new File(String.valueOf(filePath)), extensions, true);
for (File file: allMovies) {
fileList.add(file.getName());
}
Hi I have a jlist and currently it is viewing a folder + subfolders... Now i would like to change this to view the files in the subfolders as well. below please find the code I am currently using:
jList1.setModel(new javax.swing.AbstractListModel()
{
File folder = new File ("/Assignment_Datex/message_outbox/");
File[] listofFiles = folder.listFiles();
// #Override
public int getSize()
{ return listofFiles.length; }
// #Override
public Object getElementAt(int i)
{ return listofFiles[i];}
}
);
Right now as you can see in the screenshot, the Jlist is only viewing the folders and not the files in them... Any help please?
If you want to show all files and folder under some root folder then you should try someting like this...
Get files and folders under root folder.
Loop over them and check if it is file or folder.
If file then just add to list nothing more.
If folder then add it to list and repeat this same steps for that folder until all folder and files are traveled.
I can not produce whole code here but this is a prototype for this:
void addFilesToList(File folder){
File[] listofFiles = folder.listFiles();
for(File file:listofFile){
if(file.isFile()) // --- file
list.add(file.getName());
else{ // --- folder
addFileToList(file);
}
}
}
The above code is not tested so may need to modify it to fit your need.
#Harry Joy is right.
Additionally you can also use FindFile from jakarta project. It can save your time.
You create a constructor to initialise your class, and there you put (tested and working)
// initialize the class variable
listofFiles = new ArrayList();
// initialize with the path
File f = new File("/home/albertmatyi/Work/python/");
// create a temporary list to work with
LinkedList files = new LinkedList();
// fill it with the contents of your path
files.addAll(Arrays.asList(f.listFiles()));
while (!files.isEmpty()) {
// keep removing elements from the list
f = files.pop();
// if it is a directory add its contents to the files list
if (f.isDirectory()) {
files.addAll(Arrays.asList(f.listFiles()));
// and skip the last if
continue;
}
// check if it's a text file, and add it to listofFiles
if (f.getName().endsWith(".txt"))
listofFiles.add(f);
}
EDIT:
Note:
I've changed the type of listofFiles to ArrayList<File>, which has to be initialized in the constructor using:
listofFiles = new ArrayList<File>();
This allows easier manipulation of the data - no need to manually allocate bigger space for when more text files need to be added
I think this is good way to read all .txt files in a folder and sub folder's
private static void addfiles (File input,ArrayList<File> files)
{
if(input.isDirectory())
{
ArrayList <File> path = new ArrayList<File>(Arrays.asList(input.listFiles()));
for(int i=0 ; i<path.size();++i)
{
if(path.get(i).isDirectory())
{
addfiles(path.get(i),files);
}
if(path.get(i).isFile())
{
String name=(path.get(i)).getName();
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(path.get(i));
}
}
}
}
}
if(input.isFile())
{
String name=(input.getName());
if(name.lastIndexOf('.')>0)
{
int lastIndex = name.lastIndexOf('.');
String str = name.substring(lastIndex);
if(str.equals(".txt"))
{
files.add(input);
}
}
}
}
Now you have a list of files that you can do some process on it!