In Java, we can determine the size of a file with File
, FileChannel
, and Files
. If you are using Java 7 or greater, it is recommended to you Files
class.
In this tutorial, I will show several ways how to determine the file size
- Get file size with File class
- File size using FileChannel class
- Get file size with Files class
1. File size using File class
Java file.length()
method returns the size of the file in bytes. The return value is unspecified if this file denotes a directory. So before calling this method, make sure the file exists and it’s not a directory.
Below is a simple example program using File class.
package com.kodehelp.java.io;
import java.io.File;
public class GetFileSize {
public static void main(String[] args) {
File file = new File("kodehelp.txt");
if (!file.exists() || !file.isFile()) return;
System.out.println(getFileSizeBytes(file));
System.out.println(getFileSizeKiloBytes(file));
System.out.println(getFileSizeMegaBytes(file));
}
private static String getFileSizeMegaBytes(File file) {
return (double) file.length() / (1024 * 1024) + " mb";
}
private static String getFileSizeKiloBytes(File file) {
return (double) file.length() / 1024 + " kb";
}
private static String getFileSizeBytes(File file) {
return file.length() + " bytes";
}
}
2. Using FileChannel class
FileChannel
has the size()
method to determine the size of the file.
package com.kodehelp.java.io;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
public class GetFileSize {
public static void main(String[] args) {
Path filePath = Paths.get("kodehelp.txt");
try (FileChannel fileChannel = FileChannel.open(filePath)) {
long fileSize = fileChannel.size();
System.out.println(fileSize + " bytes");
} catch (Exception e) {
e.printStackTrace();
}
}
}
3. using Files class
Files
has the size()
method to determine the size of the file. This is the most recent API and it is recommended for new Java applications.
package com.kodehelp.java.io;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class GetFileSize {
public static void main(String[] args) {
try {
Path filePath = Paths.get("kodehelp.txt");
System.out.println(getFileSizeBytes(filePath));
System.out.println(getFileSizeKiloBytes(filePath));
System.out.println(getFileSizeMegaBytes(filePath));
} catch (IOException e) {
e.printStackTrace();
}
}
private static String getFileSizeMegaBytes(Path filePath) throws IOException {
return (double) Files.size(filePath) / (1024 * 1024) + " mb";
}
private static String getFileSizeKiloBytes(Path filePath) throws IOException {
return (double) Files.size(filePath) / 1024 + " kb";
}
private static String getFileSizeBytes(Path filePath) throws IOException {
return Files.size(filePath) + " bytes";
}
}