Get file size in bytes in Java
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.
|
1 2 3 4 5 6 7 8 9 10 |
import java.io.File; public class Main { public static void main(String[] args) { File file = new File("/var/system.logs"); long size = file.length(); System.out.println("The file size is " + size + " bytes"); } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class Main { public static void main(String[] args) { String filePath = "/var/system.logs"; try { long size = Files.size(Path.of(filePath)); System.out.println("The file size is " + size + " bytes"); } catch (IOException e) { e.printStackTrace(); } } } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class Main { public static void main(String[] args) { String filePath = "/var/system.logs"; try (FileInputStream fis = new FileInputStream(new File(filePath))) { long size = fis.getChannel().size(); System.out.println("The file size is " + size + " bytes"); } catch (IOException e) { e.printStackTrace(); } } } |
That’s all about getting file size in bytes in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)