Web | This Site

Java Basics Examples
Java Tutorial
Java Useful Resources
Selected Reading
© 2011 TutorialsPoint.COM

| Home |  | References |  | Discussion Forums |  | About TP

# Java Examples - File Size

## Problem Description:

How to get a file’s size in bytes ?

## Solution:

This example shows how to get a file's size in bytes by using file.exists() and file.length() method of File class.

    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:/java.txt");
          System.out.println("Filesize in bytes: " + size);
       }
    }

## Result:

The above code sample will produce the following result.To test this example, first create a text file 'java.txt' in 'C' drive.The size may vary depending upon the size of the file.

    File size in bytes: 480

Advertisement

Online Image Processing

Indian Baby Names