Java Programming Exercies

Java Exercises: Get file size in bytes, kb, mb

Java Input-Output: Exercise-9 with Solution

Write a Java program to get 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");
        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: Get file size in bytes, kb, mb

Java Practice online :

Contribute your code and comments through Disqus.

Previous: Write Java program to read input from java console.
Next: Write a Java program to read contents from a file into byte array.

What is the difficulty level of this exercise?

New Content: Composer: Dependency manager for PHP, R Programming