2: To implement a recursive algorithm to calculates the total disk usage (in byt
ID: 3881269 • Letter: 2
Question
2: To implement a recursive algorithm to calculates the total disk usage (in bytes) of the portion of the file system rooted at the given path. Program will rely on the following methods of the class: new File(pathString) or new File(parentFile,childString) · file·length() returns the immediate disk usage(measured in bytes) . file.isDirectory) Returns true if the File instance represents a directory; false otherwise . file.list) Return an array of strings designating the names of all entries within the given directory. (2 points)Explanation / Answer
/**
* Below class can be used to find the size of a directory
*
*/
public class FileInfo
{
private static long size = 0l ;
private static long getInfo(File file)
{
/*
* Null check for NULLPointerExceptions
*/
if(file != null)
{
if(file.isDirectory())
{
/*
* Recursive check for directory starts from here
*/
String arr[] = file.list() ;
for(int i =0 ; i< arr.length ; i++)
{
File f = new File(file, arr[i]) ;
/*
* Add the size of a directory
*/
size = size + f.length() ;
/*
* recursive call to function itself
*/
getInfo(f) ;
}
/*
* Recursive check for directory ends here
*/
}
else
{
/*
* A safety measure if someone passes a actual file name from main class
*
* e.g /home/neeraj/Documents/2018/january/abc.txt
*/
return file.length() ;
}
}
return size ;
}
/**
*
* Starting point of java program
*/
public static void main(String[] args)
{
/*
* Enter the directory path
*/
String directoryPath="/home/neeraj/Documents/2018/january" ;
/*
* Create file object pointing to the directory
*/
File file = new File(directoryPath) ;
/*
* Size in bytes
*/
double sizeInBytes = getInfo(file) ;
/*
* Size in MegaBytes
*/
double sizeInMB = (sizeInBytes/(1000000)) ;
/*
* Display size in bytes and megabytes of given path
*/
System.out.println(directoryPath +" total size in bytes " + sizeInBytes) ;
System.out.println(directoryPath +" total size in MB " + sizeInMB) ;
}
}
Sample output:
/home/neeraj/Documents/2018/january total size in bytes 2101401.0
/home/neeraj/Documents/2018/january total size in MB 2.101401
Note:
If you are using windows and facing any problem with changing directoryPath variable.
Then try giving double forward slash(//) instead of single forwardslash(/). Or just comment on my answer in case you face any difficulty.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.