Using File#length() method A simple solution is to call the File#length() method that returns the size of the file in bytes. To get the file size in MB, you can divide the length (in bytes) by 1024 * 1024 .
Java get file size using File classJava File length() method returns the file size in bytes.
To get the total size of a directory in Linux, you can use the du (disk-usage) command.
You can use the length()
method on File
which returns the size in bytes.
You don't need FileInputStream to calculate file size, new File(path_to_file).length()
is enough. Or, if you insist, use fileinputstream.getChannel().size()
.
You can do that simple with Files.size(new File(filename).toPath())
.
public static void main(String[] args) {
try {
File file = new File("test.txt");
System.out.println(file.length());
} catch (Exception e) {
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With