In: Computer Science
To implement a recursive algorithm to calculates the total directory size (in bytes) of the portion of the file system rooted at the given path.
Program will rely on the following methods of the class:
The code is :
import java.io.File;
public class FileSize
{
static long findSize(File[] arr,int index,long
size)
{
if(index == arr.length)
return
size;
if(arr[index].isFile())
size = size +
arr[index].length();
else
if(arr[index].isDirectory())
size = size +
findSize(arr[index].listFiles(), 0,0);
return (size +
findSize(arr,++index,0));
}
public static void main(String[] args)
{
String path =
"/home/shrutina/DSAAssingments";
File dir = new File(path);
long size;
if(dir.exists() &&
dir.isDirectory())
{ File arr[] =
dir.listFiles();
size =
findSize(arr,0,0);
System.out.println("File size is "+size);
}
}
}
Output: