Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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");
        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

Java Code Editor:

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?

Test your Programming skills with w3resource's quiz.



Java: Tips of the Day

How to sort an ArrayList?

Collections.sort(testList);
Collections.reverse(testList);

That will do what you want. Remember to import Collections though!

Ref: https://bit.ly/32urdSe