Java File length() method with examples

April 28, 2020 No comments Java IO File Examples length

1. Introduction

The length() method from Java IO returns the length of the file. If given File object represents the directory the method will return unspecified value.

2. Method signature

public long length()

Parameters:

  • method does not take any parameter

Returns

  • long - the file lenght in bytes, or 0L if the file does not exist

Throws

  • SecurityException - when we do not have access to the file or directory

3. Examples

3.1. Print length of the file that does not exist and file with a short text inside

package com.frontbackend.java.io;

import java.io.File;
import java.time.Instant;

public class FrontBackend {

    public static void main(String args[]) {

        try {
            File f1 = new File("/tmp/frontbackend.txt"); // does not exist
            File f2 = new File("/tmp/exists.txt");

            System.out.printf("/tmp/frontbackend.txt - %s%n", f1.length()); // 0
            System.out.printf("/tmp/exists.txt - %s%n", f2.length());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

The output:

/tmp/frontbackend.txt - 0
/tmp/exists.txt - 20

4. Conclusion

In this article, we presented a method that returns the length of the file in bytes.

{{ message }}

{{ 'Comments are closed.' | trans }}