Get file size in Java

Description

The following code shows how to get file size.

Example


//  w w w  .j  av  a  2  s  .  co m
import java.io.File;

public class Main {

  public static long getFileSize(String filename) {
    File file = new File(filename);

    if (!file.exists() || !file.isFile()) {
      System.out.println("File doesn\'t exist");
      return -1;
    }
    return file.length();
  }

  public static void main(String[] args) {
    long size = getFileSize("c:/my.txt");
    System.out.println("Filesize in bytes: " + size);
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip