This post is about a program that will be able to list all files in your computer's hard disk. This code uses java.io package for this purpose. Here I have use File class to list all the drives of your hard disk using listRoots() function. Then I have defined a recursive function that will go on till all the listings are over. The recur function takes in a File as parameter and if it is a file the it displays its absolute path and if it is a directory then again it lists all its contents and for each of its contents it calls the recur function recursively. Here is the code for you :
import java.io.*;
public class FileList {
static void recur(File f1){
if (f1.isFile()){
System.out.println(f1.getAbsolutePath()); //displays path for a file
return;
}
else{
File f[]=f1.listFiles(); //lists all contents if a directory
for (int j = 0; j<f.length; j++)
try{
recur(f[j]); //calls recur for each content of directory
}catch(Exception e){e.printStackTrace();}
}
}
public static void main(String[] args){
File []A=File.listRoots(); //lists all drives
try{
for(int i=0;i<A.length;i++)
recur(A[i]); //calls recur for each drive
}catch(Exception e){e.printStackTrace();}
}
}
import java.io.*;
public class FileList {
static void recur(File f1){
if (f1.isFile()){
System.out.println(f1.getAbsolutePath()); //displays path for a file
return;
}
else{
File f[]=f1.listFiles(); //lists all contents if a directory
for (int j = 0; j<f.length; j++)
try{
recur(f[j]); //calls recur for each content of directory
}catch(Exception e){e.printStackTrace();}
}
}
public static void main(String[] args){
File []A=File.listRoots(); //lists all drives
try{
for(int i=0;i<A.length;i++)
recur(A[i]); //calls recur for each drive
}catch(Exception e){e.printStackTrace();}
}
}
No comments:
Post a Comment