How to get a file’s size in bytes in java

  • by

How to get file size in byte:-
This example shows how to get a file’s size in bytes by finding the file f.exist(), returing the length of file f.length() if file is exist and get file size of existing file size getFileSize() method
import java.io.File;
public class Main
{
public static long getFileSize(String filename)
{
File f = new File(filename);
if (!f.exists() || !f.isFile())
{
System.out.println(“File doesn\’t exist”);
return -1;
}
return f.length();
}
public static void main(String[] args)
{
long size = getFileSize(“c:/java.txt”);
System.out.println(“Filesize in bytes: ” + size);
}
}

Output:-
Display file size in bytes

Leave a Reply