Showing posts with label file size. Show all posts
Showing posts with label file size. Show all posts

Wednesday, 11 March 2020

Get File size in java

Below snippets are used to return the file size in bytes, Kbs, Mbs and Gbs.
private static long fileSizeInBytes(String filePath) {
 long length = new File(filePath).length();
 return length;
}

private static double fileSizeInKb(String filePath) {
 double length = (double) new File(filePath).length();
 return length / 1024;
}

private static double fileSizeInMB(String filePath) {
 double length = (double) new File(filePath).length();
 return length / (1024 * 1024);
}

private static double fileSizeInGb(String filePath) {
 double length = (double) new File(filePath).length();
 return length / (1024 * 1024 * 1024);
}

Find the below working application.

App.java
package com.sample.app;

import java.io.File;

public class App {

 private static long fileSizeInBytes(String filePath) {
  long length = new File(filePath).length();
  return length;
 }

 private static double fileSizeInKb(String filePath) {
  double length = (double) new File(filePath).length();
  return length / 1024;
 }

 private static double fileSizeInMB(String filePath) {
  double length = (double) new File(filePath).length();
  return length / (1024 * 1024);
 }

 private static double fileSizeInGb(String filePath) {
  double length = (double) new File(filePath).length();
  return length / (1024 * 1024 * 1024);
 }

 public static void main(String[] args) {
  String filePath = "/Users/krishna/Documents/TechnicalDocuments/glob.txt";

  System.out.println("File size : " + fileSizeInBytes(filePath) + " bytes");
  System.out.println("File size : " + fileSizeInKb(filePath) + " Kb");
  System.out.println("File size : " + fileSizeInMB(filePath) + " Mb");
  System.out.println("File size : " + fileSizeInGb(filePath) + " Gb");

 }

}

Output

File size : 2872 bytes
File size : 2.8046875 Kb
File size : 0.00273895263671875 Mb
File size : 2.6747584342956543E-6 Gb


You may like