Java: Get file size in bytes, kb, mb
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:
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics