I am using the following recursive method to list all files and folders within a given directory, however it seems to be listing some files that aren't visible in Windows Explorer - even when I display hidden and system protected files. I have set the method to scan the C:\\ directory, and it hangs after outputting files in the Boot directory and BOOTSECT.BAK. Well, actually, I don't think it hangs - it looks like it returns the final array but there are still more Files and no exceptions are thrown!
private static ArrayList<File> recursiveSearch(File dir){
File[] files = dir.listFiles();
ArrayList<File> result = new ArrayList<File>();
for(File file : files)
if(file.isDirectory()){
result.add(file);
ArrayList<File >tempList = recursiveSearch(file);
for(File temp : tempList)
result.add(temp);
}else{
result.add(file);
System.out.println(file.getPath());
}
return result;
}
I know about FileSystemView but in this occassion I can't use it because I need to apply a custom Filename Filter (which I have excluded from the above, but I have tested and it doesn't affect the methods output). Any help would be appreciated - thanks in advance
This file (bootsect.bak) is detected as a directory, yet returns a null File array. A workaround is to check that it is instantiated:
private static List<File> recursiveSearch(File dir) {
File[] files = dir.listFiles();
List<File> result = new ArrayList<File>();
if (files != null) {
for (File file : files)
if (file.isDirectory()) {
result.add(file);
List<File> tempList = recursiveSearch(file);
for (File temp : tempList)
result.add(temp);
} else {
result.add(file);
System.out.println(file.getPath());
}
}
return result;
}
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.
I have a folder in a directory. I know, there is always only one file and it's a .txt file. But I don't know the filename.
How can I access it in Java? How must the path look like?
You could open the directory and go over its contents until you find the file:
public static File getTextFileInDirectory(String dirPath) {
File dir = new File(dirPath);
for (File f : dir.listFiles()) {
if (f.isFile() && f.getName().endsWith(".txt")) {
return f;
}
}
return null;
}
EDIT:
Based on the comments below, if it's safe to assume the directory always has a file in it, and there's nothing else in the directory (e.g., subdirectories), this code can be greatly simplified:
public static File getTextFileInDirectory(String dirPath) {
return new File(dirPath).listFiles()[0];
}
Since you know there will only be one file in the directory, you can get an array of the directory's files and return the first element if it exists, or null if it doesn't.
public static File getFileFromDir(File directory) {
File[] dirFiles = directory.listFiles();
return dirFiles.length > 0 ? dirFiles[0] : null;
}
I'm creating a java program which takes parent path and deletes all the files and folders in the given path. I'm able to delete files and folder's files inside another folder in the parent folder but not able to delete folders at 3rd level.
Here's my code:
package com.sid.trial;
import java.util.List;
import java.io.File;
import java.util.ArrayList;
public class DeleteFilesOfDirectoryWithFilters {
public static void main(String[] args) {
String parentPath = "D:\\tester";
List<String> folderPaths = deleteFiles(parentPath);
deleteFolders(folderPaths);
}
public static void deleteFolders(List<String> folderPaths) {
for(String path : folderPaths){
File folder = new File(path);
if(folder.delete())
System.out.println("Folder "+folder.getName()+" Successfully Deleted.");
}
}
public static List<String> deleteFiles(String path){
File folder = new File(path);
File[] files = folder.listFiles();
List<String> folderPaths = new ArrayList<String>();
String folderPath = path;
if(files.length == 0){
System.out.println("Directory is Empty or No FIles Available to Delete.");
}
for (File file : files) {
if (file.isFile() && file.exists()) {
file.delete();
System.out.println("File "+file.getName()+" Successfully Deleted.");
} else {
if(file.isDirectory()){
folderPath = file.getAbsolutePath();
char lastCharacter = path.charAt(path.length()-1);
if(!(lastCharacter == '/' || lastCharacter == '\\')){
folderPath = folderPath.concat("\\");
}
/*folderPath = folderPath.concat(file.getName());*/
System.out.println(folderPath);
folderPaths.add(folderPath);
}
}
}
for(String directoryPath : folderPaths){
List<String> processedFiles = new ArrayList<String>();
processedFiles = deleteFiles(directoryPath);
folderPaths.addAll(processedFiles);
}
return folderPaths;
}
}
You can use the ""new"" Java File API with Stream API:
Path dirPath = Paths.get( "./yourDirectory" );
Files.walk( dirPath )
.map( Path::toFile )
.sorted( Comparator.comparing( File::isDirectory ) )
.forEach( File::delete );
Note that the call to sorted() method is here to delete all files before directories.
About one statement, and without any third party library ;)
You should consider using Apache Commons-IO. It has a FileUtils class with a method deleteDirectory that will recursively delete.
Note: Apache Commons-IO (as for version 2.5) provides utilities only for legacy java.io API (File and friends), not for Java 7+ java.nio API (Path and friends).
You can recursively traverse through the folder and delete each file one by one. After deleting all the files in one folder, delete the folder. Something similar to following code should work:
public void delete(File path){
File[] l = path.listFiles();
for (File f : l){
if (f.isDirectory())
delete(f);
else
f.delete();
}
path.delete();
}
You can do the following, your recursion is longer than needed.
public static void deleteFiles (File file){
if(file.isDirectory()){
File[] files = file.listFiles(); //All files and sub folders
for(int x=0; files != null && x<files.length; x++)
deleteFiles(files[x]);
}
else
file.delete();
}
Explanation:
When invoke deleteFiles() on a file, the else statement gets triggered, the single file will be deleted with no recursion.
When invoke deleteFiles() on a folder, the if-statement gets triggered.
Get all the entries (files of folders residing in the folder) as an array
If there exist sub-entries, for each entry, recursively delete the sub-entry (the same process (1 and 2) repeats).
Be careful when implementing deletion of file and folders. You may want to print out all the files and folders name first instead of deleting them. Once confirmed it is working correctly, then use file.delete().
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
}
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.