Program to Find file size in bytes, Kilobytes, megabytes and gigabytes using length method of File in java




File's length() method of File is used to find file size in bytes
Method return file length in bytes.  





Program to find Find file size in bytes, Kilobytes, megabytes and gigabytes using length method of File in java >




/** JavaMadeSoEasy.com */
import java.io.File;
public class FileSize {
   public static void main(String[] args) {
          String fileName = "c:/myTxt.txt";
          File file = new File(fileName);
          /*
          * length() method of File is used to find file size in bytes Method
          * return file length in bytes.
          */
         
          long fileSizeInBytes = file.length();
         
          //1 kilobyte = 1024 byte
          float fileSizeInKB = file.length() / 1024;
         
          //1 megabyte = 1024 kilobyte
          //or
          //1 megabyte = 1024 * 1024 byte
          float fileSizeInMB = fileSizeInKB / 1024;
         
          //1 gigabyte = 1024 megabyte
          //or
          //1 gigabyte = 1024 * 1024 * 1024 byte
          float fileSizeInGB = fileSizeInMB / 1024;
         
          //1 terabyte = 1024 gigabyte
          //or
          //1 terabyte = 1024 * 1024 * 1024 * 1024 byte
          float fileSizeInTB = fileSizeInGB / 1024;
          System.out.println(fileName + " size in bytes = " + fileSizeInBytes);
          System.out.println(fileName + " size in kilobytes = " + fileSizeInKB);
          System.out.println(fileName + " size in megabytes = " + fileSizeInMB);
          System.out.println(fileName + " size in gigabytes = " + fileSizeInGB);
          System.out.println(fileName + " size in terabytes = " + fileSizeInTB);
   }
}
/*OUTPUT
c:/myTxt.txt size in bytes = 14157000
c:/myTxt.txt size in kilobytes = 13825.0
c:/myTxt.txt size in megabytes = 13.500977
c:/myTxt.txt size in gigabytes = 0.013184547
c:/myTxt.txt size in terabytes = 1.2875535E-5
*/


RELATED LINKS>

Create File using createNewFile() method in java file IO


Program to Hide and unHide File or Directory (by executing CMD commands in java program) till java6 - file IO


Program on How to hide and unHide file or Directory in java 7 using java.nio.file


Program on How to Compare two file or Directory path - in java file IO




eEdit
Must read for you :