We can get File size in java by 2 methods.
1.
java.io.File API’s
length() method
2.
java.nio.file.Files API’s
readAttributes() method.
In this post we will see examples on how to get file size in java by these 2 methods.
1. Example : File Size in Java using length()
length() method returns the size of the file in bytes. You can use this to compute File size in various formats.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
package com.kscodes.sampleproject; import java.io.File; public class FileSizeExample1 { public static void main(String[] args) { File file = new File("C:\\kscodes\\work\\test.txt"); long fileSize = file.length(); System.out.println("The File Size in Bytes is ::" + fileSize); } } |
Output
1 |
The File Size in Bytes is ::1560 |
If the File doesn’t exist in the given path, the the length method returns 0
2. Example : File Size in Java using readAttributes()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package com.kscodes.sampleproject; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.BasicFileAttributes; public class FileSizeExample2 { public static void main(String[] args) { Path path = Paths.get("C:\\kscodes\\work\\test.txt"); try { BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class); long fileSize = attrs.size(); System.out.println("The File Size in Bytes is ::" + fileSize); } catch (IOException e) { System.err.println("Error occurred"); } } } |
Output
1 |
The File Size in Bytes is ::1560 |