Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: How to Get the size of a file in bytes

  1. #1
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    United Kingdom
    My Mood
    Thanked 294 Times in 227 Posts
    Blog Entries

    Post How to Get the size of a file in bytes

    This code will print the size of a file in bytes to the console.

    import java.io.File;
    public class FileSize {
         * JavaProgrammingForums.com
         public long getFileSize(String filename) {
                File file = new File(filename);
                if (!file.exists() || !file.isFile()) {
                  System.out.println("File does not exist");
                  return -1;
                // Code to get file size
                return[B] file.length();[/B]
        public static void main(String[] args) {
            FileSize fs = new FileSize();
            long size = fs.getFileSize("myFile.txt");
            System.out.println("File size in bytes " + size);
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  2. #2
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    My Mood
    Thanked 105 Times in 90 Posts

    Default Re: How to Get the size of a file in bytes

    Great idea JavaPf. I would just like to post this link to the JavaDocs for the File object as there are alot of easy to follow functions that can give you information about files and folders. For this reason I feel it may be usefull to have a link to the JavaDocs. If anyone has a problem implementing one of the functions you are more than welcome to question us on how to use it.

    File (Java 2 Platform SE v1.4.2)


Similar Threads

  1. How to Change JTextArea font, font size and color
    By Flash in forum Java Swing Tutorials
    Replies: 7
    Last Post: January 14th, 2012, 10:47 PM
  2. How to set the Listbox size.
    By jacinto in forum AWT / Java Swing
    Replies: 4
    Last Post: June 22nd, 2009, 07:39 AM

Tags for this Thread