I want to get the size of a folder and also the size of files in that folder but the output is zero even though I used the java long method for file size and a for loop to access the files in the folder.The programme only outputs the size of individual files (those that are not stored in any folder) and gives the folder size and the size of files in the folder as zero.How can I fix this so that the code reads the folder size and also the size of files in that folder?

 import java.io.*;

    public class FileSize{
       public static void main(String[] args) throws IOException{

         System.out.print("Please Enter file or Folder name : ");
         BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
         File f = new File(in.readLine());


         if(f.isFile()) {

           long file_size = f.length();

           System.out.println("File Name Is:" +f.getName());
           System.out.println("File Size:" +file_size+ "Bytes");


         }
         else if(f.isDirectory()){
            long file_size = f.length();
            File[] filesInDirectory = f.listFiles();
            System.out.println("Size Of The Directory is:" +file_size);


             System.out.println("The Files in the Directory:");
             for(int i =1;i<filesInDirectory.length; i++)
             {


               System.out.println("Name Of File Number " +i+" Is:"+filesInDirectory[i]);
               System.out.println("Size In Bytes Is:"+file_size);

             }


         }
         else{
             System.out.println("File does not exist");
         }



      }


   }

Edited 3 Years Ago by mike_2000_17: Fixed formatting

You are using the length() method for a File object that is a directory. The API reference says:
The return value is unspecified if this pathname denotes a directory.
so that's why you get 0.
You will have to sum the sizes of the individual files in the directory to get the total dir size.

Ok thanx, now I get it.I had seen that message in the API reference but thought that if I use a for loop to access the individual files in the directory then the method can also work on the files.

How can I modify the code so that it works with a number of nested folders to get their sizes

Edited 6 Years Ago by NPOT: n/a

This article has been dead for over six months. Start a new discussion instead.