0

Hello sorry for my english but I need a little help here, this must be easy for you but I for the life of me cannot figure it out. What I am trying to do is list the disk partitions and listing all the name of directory and files within them. Thus far I have reached this:

File[] root= File.listRoots();        

System.out.println("Se encontraron " + root.length + " Particiones de Disco " );

for( int i = 0 ; i < root.length ; i++ ){
    System.out.println( root[i].toString() + " existe= " + root[i].exists() );
    if(root[i].exists()==true){
        System.out.println("Espacio Total: "+ root[i].getTotalSpace());
        System.out.println("Espacio Libre: "+ root[i].getFreeSpace());

        String[] listaDeArchivos = root[i].list();
        for(String lista:listaDeArchivos){
            System.out.println(lista);
        }
    }
}

With this i get to list hard disk divitions and the first row of files in them, but i need a cycle that list all of it, all the files within the files.

DanielBarbarian
  • 5,093
  • 12
  • 35
  • 44
  • What is your question? What are you having trouble with? – Peter Lawrey Aug 23 '16 at 01:34
  • I want to print the name of all the directory and files of the hard disk – user3362366 Aug 23 '16 at 01:37
  • Welcome to Stack Overflow. You can improve your question. Please read [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve). When your code shows your precise problem with nothing extra, you are showing respect to those who volunteer to help you. Additionally, please format your code for readability and eliminate scrolling. – zhon Aug 23 '16 at 01:47
  • Do you mean like http://stackoverflow.com/questions/29395635/how-can-i-get-all-the-list-of-directories-and-files-in-a-drive-in-java-all-fil or http://stackoverflow.com/questions/14676407/list-all-files-in-the-folder-and-also-sub-folders – Peter Lawrey Aug 23 '16 at 01:56
  • Make a simple recursive method that list dir/file in directory. – Nam Tran Aug 23 '16 at 03:35

1 Answers1

0

You need to design a recursive function to list all the directories and all the files within each directory.

In the below code, the function listStructure serves this purpose.
Call this function from inside of your for loop

for(String lista:listaDeArchivos){
       System.out.println(lista);
        listStructure(lista);
        }

Function to list the directory structure.

public void listStructure(String fileName)
{
File file=new File(fileName);
if(!file.exists())
{
System.out.println(fileName+"  doesn't exists");
return;
}
if(!file.isDirectory())//check whether it's a directory or not
{
System.out.println(fileName);
return;
}
String files[]=file.list();  //if it's a directory then iterate through the directory
for(int i=0;i<files.length;i++)
{
listStructure(fileName+File.separator+files[i]);//recursively calling the function
}
}
asad_hussain
  • 1,959
  • 1
  • 17
  • 27