Recursively find all text files in directory - java

I am trying to get the names of all of the text files in a directory. If the directory has subdirectories then I also want to get any text files in those as well. I am not sure how to make the process continue for any number of subdirectories.
Right now the code below just gets all the text files in the current directory and and subdirectories in the directory. For each subdirectory found, it also finds any text files and deeper subdirectories. The problem is that if those deeper subdirectories have yet deeper subdirectories then I am not finding all the text files. This seems to be a problem that requires recursion because I don't know how deep this will go.
Here is my code so far:
File rootDirectory = new File(rootDir);
if (rootDirectory.isDirectory()) {
System.out.println("Valid directory");
File[] listOfFiles = rootDirectory.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
String iName = listOfFiles[i].getName();
if (listOfFiles[i].isFile()) {
if (iName.endsWith(".txt") || iName.endsWith(".TXT")) {
System.out.println("File: "+iName);
}
}
if (listOfFiles[i].isDirectory()) {
System.out.println("Directory: "+iName);
File[] subList = listOfFiles[i].listFiles();
for (int j = 0; j < subList.length; j++) {
String jName = subList[j].getName();
if (subList[j].isFile()) {
if (jName.endsWith(".txt") || jName.endsWith(".TXT")) {
System.out.println("\tFile: "+jName);
}
}
if (subList[j].isDirectory()) {
System.out.println("\tDirectory: "+jName);
}
}
}
}
}
else System.out.println("Invalid directory");
Edit: Got it working, thank you Olaf Dietsche:
public void findFiles(File root, int depth) {
File[] listOfFiles = root.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
String iName = listOfFiles[i].getName();
if (listOfFiles[i].isFile()) {
if (iName.endsWith(".txt") || iName.endsWith(".TXT")) {
for (int j = 0; j < depth; j++) System.out.print("\t");
System.out.println("File: "+iName);
}
}
else if (listOfFiles[i].isDirectory()) {
for (int j = 0; j < depth; j++) System.out.print("\t");
System.out.println("Directory: "+iName);
findFiles(listOfFiles[i], depth+1);
}
}
}

This is a recursive problem
public void find_files(File root)
{
File[] files = root.listFiles();
for (File file : files) {
if (file.isFile()) {
...
} else if (file.isDirectory()) {
find_files(file);
}
}
}

using the java.nio.file capabilites of java 7. I implemented similiar func. and added some test.
Benchmarks when searching for .txt on my PC
"c:/" "c:/windows"
file.io 36272ms 14082ms
file.nio 7167ms 2987ms
Read more in the javadoc, it's quite powerfull API
java.nio.file.filevisitor javadoc
public static void main(String[] args) {
long starttime = System.currentTimeMillis();
try {
Path startPath = Paths.get("c:/");
Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult preVisitDirectory(Path dir,
BasicFileAttributes attrs) {
System.out.println("Dir: " + dir.toString());
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
if (file.toString().endsWith(".txt")){
System.out.println(file.toString());
}
return FileVisitResult.CONTINUE;
}
#Override
public FileVisitResult visitFileFailed(Path file, IOException e) {
return FileVisitResult.CONTINUE;
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
long completetime = System.currentTimeMillis() - starttime;
System.out.println("totaltime=" + completetime);
}

The answer is in the tags of your question. Use recursion. Recursion consists in having a method call itself.
In this case, the method should print all the text files directly under a given directory, and call itself for every subdirectory of the directory.

Related

Java deleting folder and sub-folder 4th level

I want delete folder (directory) and sub-directory in JAVA, I need 2 conditions when there's file and where the folder is empty. I've been searched and trying all example I found, but not worked. Even when that code works, that just delete the file or just 1 folder (directory level 4) not all folder.
I want to delete old directory year\place\owner\month\file.
File source = new File("C:\\Users\\Workspaces\\projects\\uploadFolder\\year\\place\\owner\\month\\file");
Path sources = source.toPath();
I've tried this:
public static void rmdir(final File folder) {
if (folder.isDirectory()) {
File[] list = folder.listFiles();
if (list != null){
for (int i = 0; i < list.length; i++){
File tmpF = list[i];
if (tmpF.isDirectory()) {
rmdir(tmpF); }
tmpF.delete();}
}
if (!folder.delete()){
System.out.println("can't delete folder : " + folder);}}
}
This:
public static void deleteDirectory(File path)
{
if (path == null)
return;
if (path.exists())
{
for(File f : path.listFiles())
{
if(f.isDirectory())
{
deleteDirectory(f);
f.delete();
}
else
{
f.delete();
}
}
path.delete();
}
}
This :
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]);
file.delete();
}
}
This:
FileUtils.deleteDirectory(source);
This:
Files.delete(sources);

Deleting Files and Directories not working

I am trying to delete all the files inside a directory then the directory afterwards using the below code but it doesn't seem to work. (Files are not deleted after the method ran).
public void DeleteDirectory() {
ArrayList<File> Directories = new ArrayList<File>();
Directories.add(new File(Environment.getExternalStorageDirectory().toString().concat("/AssetControl/Images")));
Directories.add(new File(Environment.getExternalStorageDirectory().toString().concat("/AssetControl/Thumbnails")));
ListIterator<File> itr = Directories.listIterator();
while (itr.hasNext()) {
File dir = itr.next();
if (dir.isDirectory()) {
String[] files = dir.list();
for (int i = 0; i < files.length; i++) {
(new File(files[i])).delete();
// This is also not working:
// File current = new File(files[i]);
// current.delete();
}
dir.delete();
}
}
}
This worked for me:
replaced String[] files with File[] files.
while (itr.hasNext()) {
File dir = itr.next();
if (dir.isDirectory()) {
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
DeleteFile(files[i]);
}
dir.delete();
}
}

Drive detection only detecting one drive?

Hello all I am using if (canRead && canWrite && !isFloppy && isDrive) and it only will read off the first drive it finds "C:\", I have a HDD and a SSD, it wont detect the ssd for somereason "D:\" for some reason anyehelp? Thanks.
Sorry guys slipped my mind to include the vars:
package javaapplication3;
import java.io.*;
import javax.swing.filechooser.FileSystemView;
class filler
{
public static void main(String ar[]) throws InterruptedException
{
FileSystemView fsv = FileSystemView.getFileSystemView();
File[] f = File.listRoots();
for (int i = 0; i < f.length; i++) {
String drive = f[i].getPath();
String displayName = fsv.getSystemDisplayName(f[i]);
String type = fsv.getSystemTypeDescription(f[i]);
boolean isDrive = fsv.isDrive(f[i]);
boolean isFloppy = fsv.isFloppyDrive(f[i]);
boolean canRead = f[i].canRead();
boolean canWrite = f[i].canWrite();
//(type.toLowerCase().contains("removable") || type.toLowerCase().contains("rimovibile"))
if (canRead && canWrite && !isFloppy && isDrive) {
try {
File file = new File(drive +"log_22_2112321321312.log");
if (file.createNewFile()){
System.out.println("File is created!");
}
if (file.exists()){
System.out.println("Drive found " + drive);
file.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
}
if (canRead && canWrite && !isFloppy && isDrive &&(type.toLowerCase().contains("removable") || type.toLowerCase().contains("rimovibile"))) {
try {
File file = new File("log_22_2112321321312.log");
if (file.createNewFile()){
System.out.println("File is created!");
}
if (file.exists()){
System.out.println("Drive found " + drive);
file.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Are you using File.listRoots()? Check the output of the following:
File[] roots = File.listRoots();
for (File r : roots)
System.out.println(r);
It's possible that your SSD is being detected but isn't passing your conditional's criteria. Code inside your conditional will only be executed if the specified condition is met. Run your code without the condition to see if the drive isn't actually being recognized, or whether it's not appearing due to a logic error or some other volume setting.

Reading all files in a directory including its sub directories

This is how I set the path:
dPath = dPath.replace("\\", "/");
String iLen;
String FileName;
File iFolder = new File(dPath);
File[] listOfFiles = iFolder.listFiles();
When searching:
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
FileName = listOfFiles[i].getName();
for(String s : iEndsWith)
{
if(FileName.toLowerCase().endsWith(s))
{
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy h:mm aaa");
iLen = ReadableBytes(listOfFiles[i].length());
Object rowData[] = { FileName, listOfFiles[i].getAbsoluteFile(), sdf.format(listOfFiles[i].lastModified()), iLen };
iTableModel.addRow(rowData);
iTotalFiles ++;
}
}
}
}
That will only look for files in the given directory path, but not it's sub directories. How can I change that?
If you're on Java 7, you can use FileVisitor: http://docs.oracle.com/javase/tutorial/essential/io/walk.html
If not, just use a simple recursive version of your function.
Pass folder as Initial File which is to be searched
File foldr = new File("c:/javaFolder");
public void addFilesToList(File folder) {
File[] listofFiles = folder.listFiles();
if (listofFiles != null) {
for (File file : listofFiles) {
if (file.isFile()) {
} else
addFilesToList(file);
}
}
}
You can use DirectoryWalker from Apache Commons to walk through a directory hierarchy.

get number of files in a directory and its subdirectories

using this code
new File("/mnt/sdcard/folder").listFiles().length
returns a sum of folders and files in a particular directory without caring about subdirectories.
I want to get number of all files in a directory and its subdirectories.
P.S. : hardly matters if it returns a sum of all the files and folders.
any help appreciated,
thanks
Try this.
int count = 0;
getFile("/mnt/sdcard/folder/");
private void getFile(String dirPath) {
File f = new File(dirPath);
File[] files = f.listFiles();
if (files != null)
for (int i = 0; i < files.length; i++) {
count++;
File file = files[i];
if (file.isDirectory()) {
getFile(file.getAbsolutePath());
}
}
}
It may help you.
You can use recursion.
public static int getFilesCount(File file) {
File[] files = file.listFiles();
int count = 0;
for (File f : files)
if (f.isDirectory())
count += getFilesCount(f);
else
count++;
return count;
}
Using Java 8 NIO:
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Test {
public long fileCount(Path dir) {
return Files.walk(dir)
.parallel()
.filter(p -> !p.toFile().isDirectory())
.count();
}
public void main(String... args) {
Path dir = Paths.get(args[0]);
long count = fileCount(dir);
System.out.println(args[0] + " has " + count + " files");
}
}
public Integer countFiles(File folder, Integer count) {
File[] files = folder.listFiles();
for (File file: files) {
if (file.isFile()) {
count++;
} else {
countFiles(file, count);
}
}
return count;
}
Usage:
Integer count = countFiles(new File("your/path"), Integer.valuOf(0));
you will have to do a recursive search over your files.
Use `File#isDrirectory()ยด to check if a file is a directory and traverse the file tree down.
You have to go though all the folder recursively and find out the files
int mCount;
getTotalFiles(File dir) {
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
getTotalFiles(file);
} else {
mCount++;
}
}
}
Something I've used before, you can easily edit it to get what you want:
public class Filewalker {
public void walk( String path ) {
File root = new File( path );
File[] list = root.listFiles();
for ( File f : list ) {
if ( f.isDirectory() ) {
walk( f.getAbsolutePath() );
System.out.println( "Dir:" + f.getAbsoluteFile() );
}
else {
System.out.println( "File:" + f.getAbsoluteFile() );
}
}
}
public static void main(String[] args) {
Filewalker fw = new Filewalker();
fw.walk("c:\\" );
}
}
Here's a short one all encapsulated within a single method just returning the number of files and directories within a specific directory:
public static int countFiles(File directory) {
int count = 0;
for (File file : directory.listFiles()) {
if (file.isDirectory()) {
count += countFiles(file);
}
count++;
}
return count;
}
Cheers!
Just for the record, you may also use iteration instead of recursion:
public static int countFiles(final File dir) {
final ArrayDeque<File> dirs = new ArrayDeque<>();
dirs.add(dir);
int cnt = 0;
while (!dirs.isEmpty()) {
final File[] files = dirs.poll().listFiles();
for (final File f: files)
if (f.isDirectory())
dirs.add(f);
else
++cnt;
}
return cnt;
}
In this implementation I'm using ArrayDeque but you can use any Queue or any List for the job.
public int numberOfFiles(File srcDir) {
int count = 0;
File[] listFiles = srcDir.listFiles();
for(int i = 0; i < listFiles.length; i++){
if (listFiles[i].isDirectory()) {
count += numberOfFiles(listFiles[i]);
} else if (listFiles[i].isFile()) {
count++;
}
}
return count;
}
http://www.java2s.com/Code/Java/File-Input-Output/Countfilesinadirectoryincludingfilesinallsubdirectories.htm
public static int countFilesInDirectory(File directory) {
int count = 0;
for (File file : directory.listFiles()) {
if (file.isFile()) {
count++;
}
if (file.isDirectory()) {
count += countFilesInDirectory(file);
}
}
return count;
}
refer this site
it gives perfect answer
import java.io.File;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Path for Directory/Folder Name");
String Directory=sc.nextLine();
System.out.println("Your Directory/folder is :"+Directory);
File f = new File(Directory);
int countFiles = 0;
int countDirectory=0;
for (File file : f.listFiles()) {
if (file.isFile()) {
countFiles++;
}
if (file.isDirectory()) {
countDirectory++;
}
}
System.out.println("Number of files in Directory : " + countFiles+"\nNumber of Sub-directories "+countDirectory);
}
}

Categories

Resources