Get file size


This piece of code gets the size of a file in bytes.


import java.io.File;

public class FileUtil {

  public long getFileSize(String filename) {

    File file = new File(filename);
    
    if (!file.exists() || !file.isFile()) {
      System.out.println("File doesn\'t exist");
      return -1;
    }
    
    //Here we get the actual size
    return file.length();
  }

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





   What kind of Java example would you like to see on this site?

   
     E-mail (optional)