Sunday, June 24, 2018

Get the size of the folders

Below code snipet will print the size of the folders and files inside a given directory.

Dependency :


<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>


Below id the java code

--------------------------------------------------------------------------------------------------


package folder.size;

/**
 * Dependencies
 *
 *  https://mvnrepository.com/artifact/org.apache.commons/commons-io
 */

import java.io.File;

import org.apache.commons.io.FileUtils;

public class FolderSize {
public static void main(String[] args) {
long size = FileUtils.sizeOfDirectory(new File("C:/Folder"));

System.out.println("Folder Size: " + size + " bytes");

FolderSize folderSize = new FolderSize();
folderSize.getFirstLevelChildFolderSize("C:/Folder");
}

/**
* Get the size of the directories and files inside a given directory.
*
* @param directoryName
*            Parent directory name.
*/
public void getFirstLevelChildFolderSize(String directoryName) {
File directory = new File(directoryName);

// get all the files from a directory
File[] fList = directory.listFiles();
for (File file : fList) {
if (file.isFile()) {

long size = new File(file.getAbsolutePath()).length();
// System.out.println(file.getAbsolutePath() + "=" + size);

// System.out.println(file.getAbsolutePath() + " = "
// + FileUtils.byteCountToDisplaySize(size));

System.out.println(file.getAbsolutePath() + " , "
+ FileUtils.byteCountToDisplaySize(size));
} else if (file.isDirectory()) {
long size = FileUtils.sizeOfDirectory(new File(file.getAbsolutePath()));
// System.out.println(file.getAbsolutePath() + "=" + size);

// System.out.println(file.getAbsolutePath() + " = "
// + FileUtils.byteCountToDisplaySize(size));

System.out.println(file.getAbsolutePath() + " , "
+ FileUtils.byteCountToDisplaySize(size));
}
}

}
}

No comments:

Post a Comment