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);
}
}
Related
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);
I need help in renaming all files and folders in a directory and add a character in front of there original name.
This is a method to rename a single folder:
File from = new File(sdcard,".DCIM");
File to = new File(sdcard,"DCIM");
from.renameTo(to);
So, something like:
String path = Environment.getExternalStorageDirectory().toString()+"/MyDir";
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
file[i].renameTo(file[i].getName() + "x");
}
EDIT:
To change a file name, it might be more clear to add a temporary variable:
String name = file[i].getName();
name = name.substr(0, name.length() - 1);
file[i].renameTo(name);
Go to the root folder and iterate over it. Just check if the the folder you are accessing is a directory or not and you can write the same logic in between for every folder.
public static void renameFile(String path) throws IOException {
File root = new File(path);
File[] list = root.listFiles();
if (list == null)
return;
for (File f : list) {
if (f.isDirectory()) {
File from = new File(f,"."+f.getName());
File to = new File(f,f.getName());
from.renameTo(to);
renameFile(f.getCanonicalPath());
} else {
System.out.println("File:" + f.getAbsoluteFile());
}
}
}
public static void main(String[] args) throws IOException {
//Root path within which you want to change the folder names
renameFile("c:\rootPath");
}
Just check if this helps you.
So far I have a code like this:
import java.io.File;
import java.util.Scanner;
public class Test {
static Scanner input = new Scanner(System.in);
public static void fileListing(File[] files, int depth) {
if(depth == 0)
return;
else {
for(File file: files) {
if(file.isDirectory())
fileListing(file.listFiles(), depth-1);
else {
String ext;
String fileName = file.getName();
if(fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0)
ext = fileName.substring(fileName.lastIndexOf(".")+1);
else
return;
System.out.println(ext);
}
}
}
}
public static void main(String [] args) {
System.out.printf("Path: ");
String path = input.nextLine();
if(new File(path).isDirectory()) {
System.out.printf("Depth: ");
int depth = input.nextInt();
File[] file = new File(path).listFiles();
fileListing(file, depth);
}
else {
System.out.printf("The path %s isn't valid.", path);
System.exit(0);
}
}
}
My output lists files' extensions in a certain directory, e. g.
txt
txt
doc
How to improve this code to show files' extensions with a counter? For example above, output should look like this:
2 txt
1 doc
You can use a Map for it: The code would be:
Map<String,Integer> countExt = new HashMap<String,Integer>();
// Start from here inside your if statement
ext = fileName.substring(fileName.lastIndexOf(".")+1);
// If object already exists
if(countExt.containsKey(ext)){
Integer count = countExt.get(ext);
count++;
//Remove old object and add new
countExt.remove(ext));
countExt.put(ext,count);
}
// If extension is new
else
countExt.put(ext,1);
//For Display
Set<String> keySet = countExt.keys();
for(String key : keySet){
System.out.println(key +" : "+countExt.get(key));
}
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.
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.