w3resource

Java: Get file size in bytes, kb, mb


9. Get File Size

Write a Java program to get the file size in bytes, KB, MB.

Sample Solution:

Java Code:

import java.io.File;
 
public class Exercise9 {
 
      public static void main(String[] args) 
      {
        File file = new File("/home/students/test.txt");
        if(file.exists())
        {
        System.out.println(filesize_in_Bytes(file));
        System.out.println(filesize_in_kiloBytes(file));
        System.out.println(filesize_in_megaBytes(file));
        }
        else 
        System.out.println("File doesn't exist");
         
    }
 
    private static String filesize_in_megaBytes(File file) {
        return (double) file.length()/(1024*1024)+" mb";
    }
 
    private static String filesize_in_kiloBytes(File file) {
        return (double) file.length()/1024+"  kb";
    }
 
    private static String filesize_in_Bytes(File file) {
        return file.length()+" bytes";
    }
 }
 

Sample Output:

151 bytes                                                                                                 
0.1474609375  kb                                                                                              
1.4400482177734375E-4 mb 

Flowchart:

Flowchart: Get file size in bytes, kb, mb


For more Practice: Solve these Related Problems:

  • Write a Java program to compute the size of a file in bytes and convert it to KB and MB with appropriate rounding.
  • Write a Java program to display the sizes of all files in a directory in a human-readable format.
  • Write a Java program to compare the sizes of two files and output the difference in megabytes.
  • Write a Java program to recursively calculate the total size of all files in a directory tree.

Go to:


PREV : Read Console Input.
NEXT : Read File into Byte Array.

Java Code Editor:

Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.