Java: Get file size in bytes, kb, mb
Java Input-Output: Exercise-9 with Solution
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/java-exercises/io/java-io-exercise-9.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics