In this example, we will write a generic method to get file size in bytes, kilobytes, megabytes, GB, and TB.
File Size in B, KB, MB, GB, and TB Example
- The readableFileSize() method in the example, passes the size of the file in long type.
- The readableFileSize() method returns a String representing the file size (B, KB, MB, GB,TB).
import java.io.File;
import java.text.DecimalFormat;
/**
* This Java program demonstrates how to get file size in bytes, kilobytes, mega bytes, GB,TB.
* @author javaguides.net
*/
public class FileUtils {
/**
* Given the size of a file outputs as human readable size using SI prefix.
* <i>Base 1024</i>
* @param size Size in bytes of a given File.
* @return SI String representing the file size (B,KB,MB,GB,TB).
*/
public static String readableFileSize(long size) {
if (size <= 0) {
return "0";
}
final String[] units = new String[] {"B", "KB", "MB", "GB", "TB"};
int digitGroups = (int)(Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups))
+ " " + units[digitGroups];
}
public static void main(String[] args) {
File file = new File("sample.txt");
String size = readableFileSize(file.length());
System.out.println(size);
}
}
Output:
64 B
Increase the file and test it again.
164 KB
Reference
- https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html
- https://docs.oracle.com/javase/8/docs/api/java/io/File.html
File Handling Examples
- How to Create a New File in Java
- How to Write to File in Java
- How to delete a file in Java
- How to Copy the File in Java
- How to Move a File in Java
- How to Rename the File in Java
- How to Append to File in Java
- Read the File using BufferReader
- Read File using BufferInputStream
- Read the File using DataInputStream
- Reading a File in Java using BufferedInputStream
- Read a File in Java using BufferedReader
- Java Get File Extension From Filename
- Get File Size in Bytes KB MB GB TB
- How to Check if a File is Empty in Java
Comments
Post a Comment
Leave Comment