In this Example we learn counting files and directories in folder in Java
For this we should know about the File class in Java
Here is the Example for that
import java.io.File;
import java.util.Scanner;
public class CountFileDirectories {
static int cnt=0;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter File Path");
String str = in.next();
File file = new File(str);
showDirectoryFile(file);
}
static void showDirectoryFile(File file)
{
cnt++;
for(int i=0;i<cnt;i++)
{
if(file.isFile())
{
System.out.println(" [This is File]" + file.getName());
}
else if(file.isDirectory())
{
System.out.println("[This is Directory] " + file.getName());
File[] f = file.listFiles();
if(f!=null)
{
for (int j = 0; j < f.length; j++)
{
showDirectoryFile(f[j]);
}
}
}
}
cnt--;
}
}
here we use recursion function for counting files and directories
Regards,
Rajnikant
For this we should know about the File class in Java
Here is the Example for that
import java.io.File;
import java.util.Scanner;
public class CountFileDirectories {
static int cnt=0;
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter File Path");
String str = in.next();
File file = new File(str);
showDirectoryFile(file);
}
static void showDirectoryFile(File file)
{
cnt++;
for(int i=0;i<cnt;i++)
{
if(file.isFile())
{
System.out.println(" [This is File]" + file.getName());
}
else if(file.isDirectory())
{
System.out.println("[This is Directory] " + file.getName());
File[] f = file.listFiles();
if(f!=null)
{
for (int j = 0; j < f.length; j++)
{
showDirectoryFile(f[j]);
}
}
}
}
cnt--;
}
}
here we use recursion function for counting files and directories
Regards,
Rajnikant
No comments:
Post a Comment