This post will discuss how to get file size in bytes in Java.

1. 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. Note that the File#length() method returns length 0 if the file is a directory, or an I/O exception occurred.

Download Code

2. Using Files.size() method

Java NIO Files class provides several utility methods for operations on files. To get the size of a file in bytes, you can use the Files.size() method. Note that the actual file size might be different, due to compression, support for sparse files, or other reasons.

Download Code

3. Using FileChannel#size() method

Another option is to obtain a file input stream for the file in a file system and get the associated file channel. Then you can use the size() method that returns the current size of the channel’s file, measured in bytes.

Download Code

That’s all about getting file size in bytes in Java.