BAEL-7092: How to get the size of a file in MB, KB & GB in java (#15117)

* BAEL-7092: How to get the size of a file in MB, KB & GB in java

* Update JavaFileSizeUnitTest.java

* BAEL-7092: How to get the size of a file in MB, KB & GB in java

---------

Co-authored-by: Grzegorz Piwowarek <gpiwowarek@gmail.com>
This commit is contained in:
ACHRAF TAITAI
2023-11-15 22:16:28 +01:00
committed by GitHub
parent 1a555cd9a7
commit 0838279c6a
2 changed files with 54 additions and 5 deletions
@@ -0,0 +1,28 @@
package com.baeldung.size;
import java.io.File;
public class FileSizeUtils {
public static long getFileSizeInBytes(File file) {
if (file.exists()) {
return file.length();
} else {
throw new IllegalArgumentException("File not found.");
}
}
public static double getFileSizeInKilobytes(File file) {
long bytes = getFileSizeInBytes(file);
return (double) bytes / 1024;
}
public static double getFileSizeInMegabytes(File file) {
double kilobytes = getFileSizeInKilobytes(file);
return kilobytes / 1024;
}
public static double getFileSizeInGigabytes(File file) {
double megabytes = getFileSizeInMegabytes(file);
return megabytes / 1024;
}
}