In this source code example, we show you how to find the size of the file in Java.
We use Files.size() method to calculate the size of the given file.
Files.size() method
This method returns the size of a file (in bytes). The size may differ from the actual size of the file system due to compression, support for sparse files, or other reasons. The size of files that are not regular files is implementation-specific and therefore unspecified.Java File Size Example
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JavaFileSize {
public static void main(String[] args) throws IOException {
Path myPath = Paths.get("src/resources/bugs.txt");
long fileSize = Files.size(myPath);
System.out.format("File size: %d bytes%n", fileSize);
}
}
References
Related Java NIO Files Examples
- Java File Copy Example
- Java Create File Example
- Java Delete File Example
- Java File Size Example
- Java Get File Owner Example
- Java File Move Example
- Java Read File Example
- Java Write File Example
- Java Create Directory Example
- Java Create Multiple Directories Example
- Java List All Subdirectories From a Directory Example
- Java Append to File Example